cookieChoices = {};

Friday, 15 November 2013

C# Console Application Examples

1.C# PROGRAM TO ADD TWO NUMBERS / INTEGERS :

using System;

namespace CsharpPrograms
{
    class Program
    {
        static void Main(string[] args)
        {

            int x;
            int y;
            int result;
            Console.Write("\n Enter the first number to be added: ");
            x=Convert.ToInt32(Console.ReadLine());
            Console.Write("\n Enter the second number to be added: ");
            y = Convert.ToInt32(Console.ReadLine());
            result = x + y;
            Console.Write("\n The sum of two numbers is: "+result);
            Console.ReadLine();
        }
    }
}

2. C# PROGRAM TO ADD TWO NUMBERS / INTEGERS USING METHOD

 

using System;
 
namespace AddTwoNumsUsingFunc
{
    class Program
    {
        static void Main(string[] args)
        {
            int x, y, result = 0;
Console.WriteLine(">>>C# PROGRAM TO ADD TWO NUMBERS WITHOUT USING THIRD VARIABLE <<< ");
         Console.Write("\n Enter the first number to be added: ");
x = Convert.ToInt32(Console.ReadLine());// taking x value from keyboard
            Console.Write("\n Enter the second number to be added: ");
   y = Convert.ToInt32(Console.ReadLine()); // taking y value from keyboard
            result = Sum(x, y);     //calling function
 
            Console.WriteLine("\n The sum of two numbers is: {0} ", result);    /*printing the sum.*/
            Console.ReadLine();
        }
 
        static public int Sum(int a, int b)
        {
            int result = a + b;
            return result;
        }   
 
 
    }
}

3. C# Program To Add Two Numbers/Integers without using Third Variable :

using System;

 

namespace CsharpPrograms

{

    class Program

    {

        static void Main(string[] args)

        {

 

            int x,y;

        Console.WriteLine(">>> PROGRAM TO ADD TWO NUMBERS WITHOUT USING THIRD VARIABLE <<< ");

            Console.Write("\n Enter the first number to be added: ");

            x=Convert.ToInt32(Console.ReadLine());         // taking x value from keyboard

            Console.Write("\n Enter the second number to be added: ");

            y = Convert.ToInt32(Console.ReadLine());         // taking y value from keyboard

            x = x + y;     /*assining the value of sum of x and y to x*/

 

          Console.WriteLine("\n The sum of two numbers is: "+x);    /*printing the sum.*/

          Console.ReadLine();

        }

    }

}
 
 
4. C# PROGARM TO GET PRODUCT OF TWO NUMBERS

using System;

namespace ProductOfTwoNumbers
{
   
class Program
   
{
       
static void Main(string[] args)
       
{


           
int x, y;
           
int result;
            Console
.Write("\n Enter the first number : ");
x
= Convert.ToInt32(Console.ReadLine());  /* reading 1st number from user*/
            Console
.Write("\n Enter the second number: ");
y
= Convert.ToInt32(Console.ReadLine());  /* reading 2nd number from user*/
            result
= x * y;    /* storing the product in result*/
     Console
.WriteLine("\n The product of two numbers is: {0} \n", result);
            Console
.ReadLine();

       
}
   
}
}

5. C# program to print sum of series 1+2+3+....+n

using System;



namespace SumOfSeries

{

    class Program

    {

        static void Main(string[] args)

        {

            int sum = 0, i, n;

            Console.WriteLine("\n>>> C# Program to print Sum of Series 1+2+3+..+n <<<\n");

            Console.Write("\n Enter the number of terms:");

            n=Convert.ToInt32(Console.ReadLine());

            for (i = 1; i <= n; i++)

            {

                sum += i;

            }

            Console.WriteLine("\n Sum of series upto  {0} is : {1}", n, sum);

            Console.ReadLine();



        }

    }

}

6 . C# program to find reverse of a given number

using System;



namespace ReverseNumber

{

    class Program

    {

        static void Main(string[] args)

        {



            int num, rem, sum = 0, rev;

            Console.WriteLine("\n /** To Find Reverse Of a Number **/");

            Console.Write("\n Enter a number: ");

            num=Convert.ToInt32(Console.ReadLine());

            while (Convert.ToBoolean(num))

            {

                rem = num % 10;  //for getting remainder by dividing with 10

                num = num / 10; //for getting quotient by dividing with 10

                sum = sum * 10 + rem;

            }

            rev = sum;

            Console.WriteLine("\n The Reversed Number is: {0} \n\n", rev);

            Console.ReadLine();

        }

    }

}

7. C# Program to find whether the Number is Palindrome or not
using System;


namespace NumberPalindrome
{
    class Program
   
{
       
static void Main(string[] args)
       
{
           
int num, rem, sum = 0, temp;
           
//clrscr();
            Console
.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
            Console
.Write("\n Enter a number: ");
            num
= Convert.ToInt32(Console.ReadLine());
            temp
= num;
           
while (Convert.ToBoolean(num))
           
{
                rem
= num % 10;  //for getting remainder by dividing with 10
                num
= num / 10; //for getting quotient by dividing with 10
                sum
= sum * 10 + rem; /*multiplying the sum with 10 and adding
                           remainder*/
            
}
            Console
.WriteLine("\n The Reversed Number is: {0} \n", sum);
           
if (temp == sum) //checking whether the reversed number is equal to entered number
           
{
                Console
.WriteLine("\n Number is Palindrome \n\n");
           
}
           
else
           
{
                Console
.WriteLine("\n Number is not a palindrome \n\n");
           
}
            Console
.ReadLine();
       
}
   
}
}





8. C# Program to Find Factorial of Number

 

using System;
 
namespace FactorialOfNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, i, fact = 1;
            //clrscr();
            Console.WriteLine("\n >>C# PROGRAM TO FIND FACTORIAL OF GIVEN NUMBER <<\n");
            Console.Write("\n Enter the Number whose Factorial you want: ");
            num=Convert.ToInt32(Console.ReadLine());
            for (i = num; i >= 2; i--) //i is intializing with num value and  is decremented till 2
            {
                fact = fact * i; //fact is updating with changing value of i
            }
 
            Console.WriteLine("\n The factorial of {0} is {1}.\n\n", num, fact);
            Console.ReadLine();
        }
    }
}

9. C# PROGRAM TO PRINT SMILING FACE / ASCII VALUE OF 1 :

using System;
 
namespace SmilingFace
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1, i;
            for (i = 0; i < 250; i++) //prints love symbol 250 times
                Console.Write((char)a);  
                //Console.Write((char)1);
            Console.ReadKey();
            
        }
    }
}

10.Implementing Addition of Two Matrices Using 2D-Arrays:


using System;
namespace MatrixAdditionProgram
{
   
class Program
   
{
       
static void Main(string[] args)
       
{
           
//using 2D-ARRAYS
           
int RowSize = 5, ColSize = 5;
           
int[,] Matrix1 = new int[RowSize, ColSize];
           
int[,] Matrix2 = new int[RowSize, ColSize];
           
int[,] ResultMatrix = new int[RowSize, ColSize];
           
int i, j;


           
try
           
{
                Console
.WriteLine("\n >>> PROGRAM To PRINT ADDITION OF TWO MATRICES <<<");
                Console
.Write("\n Enter the Size of a Matrix N*N (For Example:3*3) : ");
               
string s = Console.ReadLine();
               
string[] values = s.Split('*');
                RowSize
= int.Parse(values[0]);
                ColSize
= int.Parse(values[1]);

               
if (RowSize > 5 || ColSize > 5)   //limiting the size of matrix
               
{
                    Console
.BackgroundColor = ConsoleColor.DarkRed; //changing background color to red
                    Console
.WriteLine(" The Size Of Matrix should Be in Less Than 5 (limiting size of array)");
                    System
.Console.ResetColor(); ///resetting color
                    Console
.WriteLine("\n\n\t Press Enter key to exit....");                            
                    Console
.ReadKey(); return;
               
}

               
else
               
{

                   
//Initializing all the elements to zero
                   
for (i = 0; i < RowSize; i++)
                   
{
                       
for (j = 0; j < ColSize; j++)
                       
{
                            Matrix1
[i, j] = 0;
                            Matrix2
[i, j] = 0;
                       
}
                   
}
                   
//Reading elements of Matrix1
                    Console
.WriteLine("\n Enter the elements of Matrix1({0}*{1})", RowSize, ColSize);
                   
for (i = 0; i < RowSize; i++)
                   
{
                       
for (j = 0; j < ColSize; j++)
                       
{
                            Console
.Write(" Matrix1[{0},{1}] : ", i, j);
                            Matrix1
[i, j] = Convert.ToInt32(Console.ReadLine());
                       
}
                   
}
                   
//Reading elements of Matrix2
                    Console
.WriteLine("\n Enter the elements of Matrix2({0}*{1})", RowSize, ColSize);
                   
for (i = 0; i < RowSize; i++)
                   
{
                       
for (j = 0; j < ColSize; j++)
                       
{
                            Console
.Write(" Matrix2[{0},{1}] : ", i, j);
                            Matrix2
[i, j] = Convert.ToInt32(Console.ReadLine());
                       
}
                   
}

                   
//calculating ResultMatrix, by adding Matrix1 and Matrix2
                   
for (i = 0; i < RowSize; i++)
                   
{
                       
for (j = 0; j < ColSize; j++)
                       
{
                            ResultMatrix
[i, j] = Matrix1[i, j] + Matrix2[i, j];
                       
}
                   
}

                   
//Printing Result Matrix
                    Console
.Write("\n\n\t*** Result Matrix  ***\n\n\t");
                   
for (i = 0; i < RowSize; i++)
                   
{

                       
for (j = 0; j < ColSize; j++)
                       
{
                           
if (ResultMatrix[i, j] < 10)
                           
{
                                Console
.Write("  0" + Convert.ToString(ResultMatrix[i, j])); //Making number as 01,02,etc,.
                           
}
                           
else
                           
{
                                Console
.Write("  " + Convert.ToString(ResultMatrix[i, j]));
                           
}

                            
if (j == ColSize - 1) { Console.Write("\n\t"); }

                       
}
                   
}
               
}
           
}
           
catch  //to catch exceptions,suppose string entered as aRowSize or Colsize  of matrix
           
{
                Console
.BackgroundColor = ConsoleColor.DarkRed;
                Console
.WriteLine("WARNING:only Number are allowed, Enter Correct Input");
                Console
.ResetColor();
           
}

            Console
.WriteLine("\n\n\t Press Enter key to exit....");
            Console
.ReadLine();
       
}
   
}
}
..



10. C# PROGRAM TO GET ALL FILE PATHS IN A GIVEN DIRECTORY
using System;
using System.IO;

namespace GetFileNames
{
   
class Program
   
{
       
static void Main(string[] args)
       
{
           
try
           
{
               
string FolderPath ;
               
string[] Files;
                Console
.WriteLine(" Enter the Directory Path to get File Names in it : ");
                FolderPath
=Console.ReadLine();
                Files
= Directory.GetFiles(FolderPath);
                Console
.WriteLine("\n The FilePaths in given Directory are : \n\n");
               
foreach (string FileName in Files)
               
{
                    Console
.WriteLine(FileName);
               
}
                Console
.ReadLine();
           
}
           
catch (DirectoryNotFoundException ex)
           
{
                Console
.BackgroundColor = ConsoleColor.Red;
                Console
.WriteLine("\n\n Directory Not Found..Press any key to exit...");
                Console
.ReadKey();
           
}
       
}

   
}
}


11. C# PROGRAM TO GET FILE NAMES IN THE GIVEN DIRECTORY
using System;
using System.IO;

namespace GetFileNames
{
   
class Program
   
{
       
static void Main(string[] args)
       
{
           
try
           
{
               
string FolderPath ;
               
string[] Files;
                Console
.WriteLine(" Enter the Directory Path to get File Names in it : ");
                FolderPath
=Console.ReadLine();
                Files
= Directory.GetFiles(FolderPath);
                Console
.WriteLine("\n The FileNames with extension in given Directory are : \n\n");
              
               
foreach (string FileName in Files)
               
{
                   
// Create the FileInfo object only when needed to ensure
                   
// the information is as current as possible.
                    System
.IO.FileInfo fi = null;
                   
try
                   
{
                        fi
= new System.IO.FileInfo(FileName);
                   
}
                   
catch (System.IO.FileNotFoundException ex)
                   
{
                       
// To inform the user and continue is
                       
// sufficient for this demonstration.
                       
// Your application may require different behavior.
                        Console
.WriteLine(ex.Message);
                       
continue;
                   
}
                    Console
.WriteLine("{0}", fi.Name);
                  
// Console.WriteLine("{0}", fi.Directory);  //prints filepath
                  
// Console.WriteLine("{0}", fi.DirectoryName); // prints directorypath
               
}
                Console
.ReadLine();
           
}
           
catch (DirectoryNotFoundException ex)
           
{
                Console
.BackgroundColor = ConsoleColor.Red;
                Console
.WriteLine("\n\n Directory Not Found..Press any key to exit...");
                Console
.ReadKey();
           
}
       
}

   
}
}





12.Declaring constants in C#.NET
In this article we will see a small example of using constants in c#. constants are declared with a keyword const .
The program below is to find the area and perimeter of circle in which we use const . 
In the program below we have declared PI as a constant which value is given as 3.14 
It means PI value cannot be changed either at compile time or run-time .
Any Integral or string variables can be declared as constants.
We can also declare constants as public to use it in all the classes in a program. 
using System;

namespace Constants
{
    class Program
    {
        static void Main(string[] args)
        {
            //declaring const variable PI
            const double PI = 3.14;
            Console.WriteLine("*** www.ProgrammingPosts.blogspot.com ***");
            Console.WriteLine(">>> c# Program to find Area and Perimeter of Circle <<< \n");
            Console.Write("Enter radius value: ");
            int r = Convert.ToInt32(Console.ReadLine()); //taking radius as input
            double area = PI * r * r; //getting area of circle
            Console.WriteLine("Are of circle is: " + area);

            //if we try to assign a value to PI , we get compile-time error
            //PI = 123;

            double perimeter = 2 * PI * r; //getting perimeter of circle
            Console.WriteLine("Perimeter of circle: " + perimeter);
          
            Console.Read();
        }
    }
}






No comments:

Post a Comment