Saturday, 31 October 2015

Write a Program in C# to Validate Mobile Number using Regular Expressions.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter your mobile number");
        string mobileNumber = Console.ReadLine();

        string MNregExp = @"^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}";

        if (Regex.IsMatch(mobileNumber, MNregExp))
        {
            Console.WriteLine("Mobile number is in correct format");
        }
        else
        {
            Console.WriteLine("Mobile number is in incorrect format");
        }
    }
}

Write a Program in C# using Regular Expressions to read IP Address from the user and validate it.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter Your IP Address");
        string Ip = Console.ReadLine();

        string ipregex= @"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$";

        if (Regex.IsMatch(Ip, ipregex))
        {
            Console.WriteLine("You entered ip address in correct format");
        }
        else
        {
            Console.WriteLine("ip address in invalid format");
        }
    }
}

Write a Program in C# using Regular Expressions to read an Email from the user and validate it.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter your email id");
        string email = Console.ReadLine();
        string regExpEmail= @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$";

        if (Regex.IsMatch(email, regExpEmail))
        {
            Console.WriteLine("Email in Correct format");
        }
        else
        {
            Console.WriteLine("Invalid Email format");
        }
    }
}

Regular Expressions in C#

Regular Expressions
Regular expressions are Patterns that can be used to match strings. We can call it a formula for matching strings that follow some pattern. Regular expression(s) can be considered as a Language, which is designed to manipulate text.

Regular Expressions may be used to find one or more occurrences of a pattern of characters within a string. You may choose to replace it with some other characters or perform some other tasks based on the results obtained. These patterns of characters can be simple or very complex. Regular Expressions generally comprises of two types of characters -
  1. Literal or Normal Characters such as "abcd123"
  2. Special Characters that have a special meaning such as "." Or "$" or "^" 
Due to the special characters Regular Expressions form a very powerful means of manipulating strings and text.

Meta-characters and their Description


.

Matches any single character. An example of this is the regular expression s.t would match the strings sat, sit, but not sight.

$

Matches the end of a line. For instance, the regular expression reason$ would match the end of the string "He has a reason" but not the string "He has his reasons"

^

Matches the beginning of a line. For instance, the regular expression ^Where would match the beginning of the string "Where is my cap" but would not match "Do you know Where it is " .

*

Matches zero or more occurrences of the character immediately preceding. For example, the regular expression .* means match any number of any characters.

[ ]


[c1-c2]



 
[^c1-c2]
·         Matches any one of the characters between the brackets.
For example, the regular expression s[ia]t matches sat, sit, but not set.
·         Ranges of characters can specified by using a hyphen.
For example, the regular expression [0-9] means match any digit. Multiple ranges can be specified as well. The regular expression [A-Za-z] means match any upper or lower case letter.

·         To match any character except those in the range, the complement range, use the caret as the first character after the opening bracket.
For example, the expression [^123a-z] will match any characters except 1,2, 3, and lower case letters.

|

Or two conditions together. For example (him|her) matches the line "it belongs to him" and matches the line "it belongs to her" but does not match the line "it belongs to them."

+

Matches one or more occurrences of the character or regular expression immediately preceding. For example, the regular expression 9+ matches 9, 99, 999.

?

Matches 0 or 1 occurrence of the character or regular expression immediately preceding.

{i}




{i,j}
·         Match a specific number of instances or instances within a range of the preceding character.
For example, the expression A[0-9]{3} will match "A" followed by exactly 3 digits. That is, it will match A123 but not A1234.

·         The expression [0-9]{4,6} any sequence of 4, 5, or 6 digits

\d Matches a digit character. Equivalent to [0-9].

\D Matches a non-digit character. Equivalent to [^0-9].

\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".

 \W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".

\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".

Sunday, 18 October 2015

String.Trim(), String.TrimStart() and String.TrimEnd() Methods in String in C#

using System;
class Program
{
    static void Main()
    {
        string s = "     rao12345@gmail.com     ";
        //Trim() removes white space from Beginning and end of the string
        Console.WriteLine(s.Trim()+"Done");
        //TrimStart() removes white space from Beginning of the string
        Console.WriteLine(s.TrimStart() + "Done");
        //TrimEnd() removes white space from end of the string
        Console.WriteLine(s.TrimEnd() + "Done");
    }
}

Friday, 16 October 2015

Lower case, Upper case and Substring in string in C#

using System;
class Program
{
    static void Main()
    {
        string str = "inDia Is mY CoUnTrY";
        Console.WriteLine("Displaying same input string\n");
        Console.WriteLine(str);
        Console.WriteLine("\nCalling ToLower instance method which creates new copy in lower case\n");
        Console.WriteLine(str.ToLower());
        Console.WriteLine("\nCalling ToUpper instance method which creates new copy in Upper case\n");
        Console.WriteLine(str.ToUpper());
        Console.WriteLine("\nCalling Substring instance method to start from 5th index and retrieve rest of string");
        Console.WriteLine(str.Substring(5));
        Console.WriteLine("\nCalling Substring instance method to start from 0 index to 5 length");
        Console.WriteLine(str.Substring(0, 5));
    }
}

Split a string array in C#

using System;
class Program
{
    static void Main()
    {
        string str = "India is my country";
        string[] splitArray = str.Split();
        foreach (string s in splitArray)
        {
            Console.WriteLine(s);
        }
    }
}


/*
Output :-

 India
 is
 my
 country
*/

input from user in Jagged Array Demonstration in C#

using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Please enter the number of element");
        int NoOfElement = int.Parse(Console.ReadLine());
        int[][] jaggedArray = new int[NoOfElement][];
        Console.WriteLine("Initializing each element in Jagged Array");
        for (int i = jaggedArray.GetLowerBound(0); i <= jaggedArray.GetUpperBound(0); i++)
        {
            Console.WriteLine("Please Enter the number of element in Row : {0}", i + 1);
            int colsize = int.Parse(Console.ReadLine());
            jaggedArray[i] = new int[colsize];
            Console.WriteLine("Reading Data in Jagged Array");
            for (int j = jaggedArray[i].GetLowerBound(0); j <= jaggedArray[i].GetUpperBound(0); j++)
            {
                Console.WriteLine("Please enter the value [{0} {1}]",i,j);
                jaggedArray[i][j] = int.Parse(Console.ReadLine());
            }
        }
        Console.Clear();
        Console.WriteLine("Displaying the jagged array Element");

        foreach (int[] elementArray in jaggedArray)
        {
            foreach (int element in elementArray)
            {
                Console.Write(element + "\t");
            }
            Console.WriteLine("\n");
        }
       
    }
}

simple Jagged Array Demonstration in C#

using System;
class Program
{
    static void Main()
    {
        int[][] jaggedArray = new int[5][];
        jaggedArray[0] = new int[6] { 1, 2, 3, 4, 5, 6 };
        jaggedArray[1] = new int[3] { 1, 2, 3 };
        jaggedArray[2] = new int[5] { 1, 2, 3, 4, 5 };
        jaggedArray[3] = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        jaggedArray[4] = new int[1] { 1 };

        foreach (int[] elementArray in jaggedArray)
        {
            foreach (int i in elementArray)
            {
                Console.Write(i + "\t");
            }
            Console.WriteLine("\n");
        }
    }
}

Jagged Array in C#

Jagged Arrays (array-of-arrays)

A jagged array is an array of arrays. Each element in jagged array act as an array. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can different.

Example:

int[][] jaggedArray = new int[5][];

In the above declaration the rows are fixed in size. But columns are not specified as they can vary.

Declaring and initializing jagged array.

int[][] jaggedArray = new int[5][];

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[6];

jaggedArray[2] = new int[2];

jaggedArray[3] = new int[4];

jaggedArray[4] = new int[10];


jaggedArray[0] = new int[] { 2, 3, 5, 7, 9 };

jaggedArray[1] = new int[] { 7, 1, 0, 2, 4, 6 };

jaggedArray[2] = new int[] { 2, 6 };

jaggedArray[3] = new int[] { 2, 4, 6, 45 };

jaggedArray[4] = new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray = new int[][]
{
new int[] { 2, 3, 5, 7, 9 },

new int[] { 7, 1, 0, 2, 4, 6 },

new int[] { 2, 6 },

new int[] { 2, 4, 6, 45 },

new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 }
};

You can use the following shorthand form:

int[][] jaggedArray =
{
new int[] { 2, 3, 5, 7, 9 },

new int[] { 7, 1, 0, 2, 4, 6 },

new int[] { 2, 6 },

new int[] { 2, 4, 6, 45 },

new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 }
};

Calculating the sum of a Digits in C#

using System;
class Program
{
    static void Main()
    {
        int sum = 0;
        Console.WriteLine("Enter a Number");
        int Number = int.Parse(Console.ReadLine());
        int temp = Number;
        while (temp > 0)
        {
            sum = sum + (temp % 10);
            temp = temp / 10;
        }
        Console.WriteLine("Sum of {0} Digit is : {1}",Number,sum);

    }
}

How to create non zero index based Array in C#

using System;
class program
{
    static void Main()
    {
        int[] lowerBound = { 2015, 10 };
        int[] length = { 3, 3 };
        int[,] testArray=(int[,])Array.CreateInstance(typeof(int),length,lowerBound);
       
     
        for (int i = testArray.GetLowerBound(0); i <= testArray.GetUpperBound(0); i++)
        {
            for (int j = testArray.GetLowerBound(1); j <= testArray.GetUpperBound(1); j++)
            {
                Console.WriteLine("Enter the Data [{0} {1}]",i,j);
                testArray[i, j] = int.Parse(Console.ReadLine());

            }
        }
        for (int i = testArray.GetLowerBound(0); i <= testArray.GetUpperBound(0); i++)
        {
            for (int j = testArray.GetLowerBound(1); j <= testArray.GetUpperBound(1); j++)
            {
                Console.Write("{0:C}" + "\t", testArray[i, j]);
            }

            Console.WriteLine("\n");
        }
    }
}



Perform Addition, Substraction, Multiplication of two Matrices using two Dimensional (2D) Array in C#

using System;
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Row size of Array");
            int rowsize = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the column size of array");
            int colsize = int.Parse(Console.ReadLine());
            int[,] Matrix1=new int[rowsize,colsize];

            for (int i = Matrix1.GetLowerBound(0); i <= Matrix1.GetUpperBound(0); i++)
            {
                for (int j = Matrix1.GetLowerBound(1); j <= Matrix1.GetUpperBound(0); j++)
                {
                    Console.WriteLine("Enter Data of Matrix1 [{0} {1}]",i,j);
                    Matrix1[i, j] = int.Parse(Console.ReadLine());
                }
            }
            int[,] Matrix2 = new int[rowsize, colsize];
            for (int i = Matrix2.GetLowerBound(0); i <= Matrix2.GetUpperBound(0); i++)
            {
                for (int j = Matrix2.GetLowerBound(1); j <= Matrix2.GetUpperBound(0); j++)
                {
                    Console.WriteLine("Enter Data of Matrix2 [{0} {1}]", i, j);
                    Matrix2[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.Clear();
            Console.WriteLine("\n Displaying the Data of Matrix1 \n");
            for (int i = Matrix1.GetLowerBound(0); i <= Matrix1.GetUpperBound(0); i++)
            {
                for (int j = Matrix1.GetLowerBound(1); j <= Matrix1.GetUpperBound(0); j++)
                {
                    Console.Write(Matrix1[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            Console.WriteLine("\n Displaying the Data of Matrix2 \n");
            for (int i = Matrix2.GetLowerBound(0); i <= Matrix2.GetUpperBound(0); i++)
            {
                for (int j = Matrix2.GetLowerBound(1); j <= Matrix2.GetUpperBound(0); j++)
                {
                    Console.Write(Matrix2[i,j]+"\t");
                }
                Console.WriteLine("\n");
            }
            int[,] Matrix3 = new int[rowsize, colsize];
            Console.WriteLine("Press 1 for Addition");
            Console.WriteLine("Press 2 for Substraction");
            Console.WriteLine("Press 3 for Multiplication");
            int userChoice = int.Parse(Console.ReadLine());
            switch (userChoice)
            {
           
                case 1:
                    Console.WriteLine("\n Addition of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] + Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
                    break;
                case 2:
                    Console.WriteLine("\n Substraction of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] - Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            break;
                case 3:
                    Console.WriteLine("\n Multiplication of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] * Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            break;
                default:
            Console.WriteLine("You entered invalid Option... Plz try again...");
            break;
            }
           
        }
    }

Thursday, 15 October 2015

Demonstration of multidimensional array in C#

using System;
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Number of Rows");
            int rowSize = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the Column size");
            int colSize = int.Parse(Console.ReadLine());

            object[,] employeeData = new object[rowSize, colSize];
            for (int i = employeeData.GetLowerBound(0); i <= employeeData.GetUpperBound(0); i++)
            {
                for (int j = employeeData.GetLowerBound(1); j <= employeeData.GetUpperBound(1); j++)
                {
                    Console.WriteLine("Enter the Employee Data [{0} {1}]",i,j);

                    employeeData[i, j] = Console.ReadLine();
                }
            }
            Console.WriteLine("Displaying the Employee Data");
            for (int i = employeeData.GetLowerBound(0); i <= employeeData.GetUpperBound(0); i++)
            {
                for (int j = employeeData.GetLowerBound(1); j <= employeeData.GetUpperBound(1); j++)
                {
                    Console.Write(employeeData[i, j]+"\t");
                }
                Console.WriteLine("\n");
            }
        }
    }

Single Dimensional array Demonstration in C#


using System;
class Program
{
static void Main(string[] args)
{
int[] testarray = new int[10];
for (int i = 1; i < =10; i++)
{
Console.WriteLine("Enter array element : {0}", i);
testarray[i] = int.Parse(Console.ReadLine());
}

foreach (int i in testarray)
{
Console.WriteLine(i);
}
}
}

Note: If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

Something about foreach
In a for loop, you should know the number of element of the array. If you don't, the C# language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, C# provides the foreach operator.
foreach loop is used on enumerator type only.
foreach is read-only loop.

Multidimensional Array in C#

Multidimensional arrays (rectangular arrays)

Arrays can have more than one dimension; these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier.

The most common kind of multidimensional array is the two-dimensional array. A two dimensional array can be thought of as a grid of rows and columns.

Declaring multidimensional array


string[,] names = new string[4, 4];
int[,] numbers = new int[3, 4];

Multidimensional array initialization


int[,] numbers = new int[3, 2] {{1,2}, {3,4}, {5,6}};
string[,] names = new string[2, 2] {{"Ana""Anita"}, {"Bob""Barbie"}};

You can omit the size of the array, like this:

int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] {{"Ana""Anita"}, {"Bob""Barbie"}};

You can also omit the new operator if you initialize array like this:

int[,] numbers = {{1,2}, {3,4}, {5,6}};
string[,] names = {{"Ana""Anita"}, {"Bob""Barbie"}};


Single Dimensional Array in C#

Single Dimensional Array

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array - 1.

Single Dimensional array is also called one-dimensional array.

DataType[] VariableName = new DataType[Number];

In the above declaration DataType can be char, int, float, double, decimal, string, etc.

VariableName is the name of the array.

The square brackets [] on the left of the assignment operator are used to let the compiler know that you are declaring an array instead of a normal variable.

The new operator allows the compiler to reserve memory.

The [Number] factor is used to specify the number of items of the list.

Declaring single dimensional array

int[] arr = new int[10];

double numbers = new double[5];

string[] names = new string[2];

Single dimensional array initialization


int[] numbers = new int[] { 1, 2, 3, 4, 5, 6,7,8,9,10 };

string[] names = new string[] { "Rocky""Sam""Tina""Yoo""James""Samantha" };

You can omit the size of the array, like this:

int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Reena""Prety""Rocky""David");

You can also omit the new operator if you initialize array like this:

int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Reena""Prety""Rocky""David"};

What is Array and Type of Array in C#

What is array?
Array is a type that holds multiple variables of one type, allowing index access to the individual value. 

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

An array in .NET is created from Array base class. Array is a reference type because it is created from array class. The base class for arrays in C# is the System.Array class.

Array is fixed type. You can create array of primitive and non-primitive types. Array base address is stored in stack and array is kept in heap memory.
System.Array is the abstract base type of all array types. Array type can't be inherited. Array can't be extended. There size is fixed. Private constructor and inner class is use to create it

Type of Arrays in C#
  • Single-dimensional arrays 
  • Multidimensional arrays (rectangular arrays) 
  • Jagged Arrays (array-of-arrays) 

Use of Rank , index of, last Index of Clone and Binary Search in Array in C#

In C# there are two types of Copy:

Deep Copy - Copying the Address
Shallow Copy - Copying the value
Clone() - Creates a copy of Shallow Copy

For Binary Search array must be sorted

using System;
    class Program
    {
        static void Main(string[] args)
        {
            int[] testArray = new int[] { 25, 10, 20, 5, 30, 1, 15, 28 };
            Console.WriteLine(testArray.Rank);
            Array.Sort(testArray);
            Console.WriteLine(Array.IndexOf(testArray, 100));
            Console.WriteLine(Array.LastIndexOf(testArray,20));
            int[] clonearray = (int[])testArray.Clone();
            //For Binary Search array must be sorted
            Console.WriteLine(Array.BinarySearch(testArray, 10));
        }
    }

Sort the Element of Array without using function in C#

using System;
class Program
{
    static void Main()
    {
        int[] testarray = new int[] { 10, 5, 15, 85, 25, 65, 84, 17, 28 };
 
        int temp = 0;

        for (int i = 0; i < testarray.Length; i++)
        {
            for (int j = 0; j < testarray.Length - 1; j++)
            {
                if (testarray[j] > testarray[j + 1])
                {
                    temp = testarray[j + 1];
                    testarray[j + 1] = testarray[j];
                    testarray[j] = temp;
                }
            }
        }
       
        foreach (int i in testarray)
        {
            Console.Write(i + "\t");
        }
        Console.WriteLine("\n");
    }
}

Sort the Element of Array using Sort Function

using System;
class Program
{
    static void Main()
    {
        int[] testarray = new int[] { 10, 5, 15, 85, 25, 65, 84, 17, 28 };
        Array.Sort(testarray);
        foreach (int i in testarray)
        {
            Console.Write(i + "\t");
        }
        Console.WriteLine("\n");
    }
}

Foreach Loop in C#

using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter the number of Student");
        int NumberOfStudent = int.Parse(Console.ReadLine());
        string[] student=new string[NumberOfStudent];
        for (int i = student.GetLowerBound(0); i <= student.GetUpperBound(0); i++)
        {
            Console.WriteLine("Enter the {0} Student Name", i + 1);
            student[i] = Console.ReadLine();
        }
       
        foreach (string s in student)
        {
            Console.WriteLine("Name of Student is {0}",s);
        }
    }
}

Retrieve Data from Single Dimensional array using for loop through LowerBound and UpperBound in C#

using System;
class Program
{
    static void Main()
    {
        int[] testArray = new int[5];
        testArray[0] = 10;
        testArray[1] = 20;
        testArray[3] = 40;
        for (int i = testArray.GetLowerBound(0); i <= testArray.GetUpperBound(0); i++)
        {
            Console.Write(testArray[i] + "\t");
        }
        Console.WriteLine("\n");
    }
}

Assign value to array at the time of Declaration and Accessing array element in C#

using System;
    class Program
    {
        static void Main(string[] args)
        {
            int[] testarray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            for (int i = 0; i < testarray.Length; i++)
            {
                Console.Write(testarray[i]+"\t");
            }
            Console.WriteLine("\n");
        }
    }

Find Smallest and Largest Factor of a Number using Single for loop in C#

using System;
class Program
{
    static void Main()
    {
        int i, j;
        int smallest, largest;
        smallest = largest = 1;
        Console.WriteLine("Enter a Number for Factor");
        int Number = int.Parse(Console.ReadLine());
        for (i = 2, j = Number / 2; (i <= Number / 2) && (j >= 2); i++, j--)
        {
            if ((smallest == 1) && (Number % i) == 0)
            {
                smallest = i;
            }
            if ((largest == 1) && (Number % j) == 0)
            {
                largest = j;
            }
        }
        Console.WriteLine("{0} is the smallest and {1} is the Largest factor of {2}",smallest,largest,Number);
    }
}

Fibonacci Series using for loop in C#

using System;
class Program
{
    public static void Main()
    {
        int a = 0, b = 1;
        Console.WriteLine("Please Enter your Target?");
        int target = int.Parse(Console.ReadLine());
        Console.Write(a+"\t");
        for (; b < target;)
        {
            Console.Write(b+"\t");
            b = a + b;
            a = b - a;
        }
        Console.WriteLine("\n");
    }
}

Fibonacci series in using while loop in C#

using System;
class Program
{
    public static void Main()
    {
        int Num1,Num2;
        Num1 = 0;
        Num2 = 1;
        Console.WriteLine("Enter your target?");
        int target = int.Parse(Console.ReadLine());
        Console.WriteLine(Num1);
        while (Num2 < target)
        {
            Console.WriteLine(Num2);
            Num2 = Num1 + Num2;
            Num1 = Num2 - Num1;
        }
    }
}

Find Factorial of Number in C#

using System;
class Program
{
    public static void Main()
    {
        int factor;
        Console.WriteLine("Enter a number");
        int number = int.Parse(Console.ReadLine());
        factor = number;
        for (int i = number - 1; i >= 1; i--)
        {
            factor = factor * i;
        }
        Console.WriteLine(factor);
    }
}

goto statement in C#

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("please Choose your city Name where you would like to visit");
        Console.WriteLine("Press 1 for Delhi");
        Console.WriteLine("Press 2 for Bangaluru");
        Console.WriteLine("Press 3 for Mumbai");
        Console.WriteLine("Press 4 for Mysore");
        int userChoice=int.Parse(Console.ReadLine());
       
       
        switch (userChoice)
        {
            case 1:
                Console.WriteLine("Welcome to Delhi");
                Console.WriteLine("Capital City of India");
                break;
            case 2:
                Console.WriteLine("Welcome to Bangaluru");
                Console.WriteLine("IT Hub of India");
                Console.WriteLine("We have free trip to Mysore");
                Console.WriteLine("Press Yes If you are Interested");
                string userDecision = Console.ReadLine().ToUpper();
                if (userDecision == "YES")
                {
                    goto case 4;
                }
                break;
            case 3:
                Console.WriteLine("Welcome to Mumbai");
                Console.WriteLine("Financial City of India");
                break;
            case 4:
                Console.WriteLine("Welcome to Mysore");
                Console.WriteLine("Historic City of India");
                 break;
            default:
                Console.WriteLine("You Enter Invalid Option. Plz Try again...");
                break;
        }
    }
}

Maximum number among three numbers using ternary operator in C#

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter first Number");
        int FirstNumber = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter second Number");
        int SecondNumber = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter Third Number");
        int thirdNumber = int.Parse(Console.ReadLine());

        int maxNumber = (FirstNumber > SecondNumber)? (FirstNumber>thirdNumber ? FirstNumber : thirdNumber):(SecondNumber>thirdNumber?SecondNumber:thirdNumber);
        Console.WriteLine("Maximum Number among {0}, {1} and {2} is {3}",FirstNumber,SecondNumber,thirdNumber,maxNumber);
    }
}

Maximum Number between two numbers using ternary operator in C#

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter first Number");
        int FirstNumber = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter second Number");
        int SecondNumber = int.Parse(Console.ReadLine());

        int maxNumber = FirstNumber > SecondNumber ? FirstNumber : SecondNumber;
        Console.WriteLine("Maximum Number between {0} and {1} is {2}",FirstNumber,SecondNumber,maxNumber);
    }
}

Continue statement in C#

using System;
class Program
{
    public static void Main()
    {
        int target=100;
        int i=10;
        while (i <= target)
        {
            Console.WriteLine(i);
            i = i + 10;
            if (i == 50)
            {
                continue;
            }
           
           
        }
     
    }
}

Break statement in C#

using System;
class Program
{
    public static void Main()
    {
        int target=100;
        int i=10;
        while (i <= target)
        {
            if (i >= 50)
            {
                break;
            }
            Console.WriteLine(i);
            i = i + 10;
        }
     
    }
}

Addition Substraction Multiplication and Division using Switch Statement

using System;
class Program
{
    public static void Main()
    {
        double result=0;
        Console.WriteLine("Enter First Number");
        double FN=double.Parse(Console.ReadLine());
        Console.WriteLine("Enter Second Number");
        double SN = double.Parse(Console.ReadLine());

        Console.WriteLine("Choose which action you wanna perform");
        Console.WriteLine("Press 1 for Addition");
        Console.WriteLine("Press 2 for Substraction");
        Console.WriteLine("Press 3 for Multiplication");
        Console.WriteLine("Press 4 for Division");
        int userChoice = int.Parse(Console.ReadLine());

        switch (userChoice)
        {
            case 1:
                result = FN + SN;
                break;
            case 2:
                result = FN - SN;
                break;
            case 3:
                result = FN * SN;
                break;
            case 4:
                result = FN / SN;
                break;
            default:
                Console.WriteLine("You entered invalid number. Please try again...");
                break;
        }
        Console.WriteLine("Result is = {0}",result);
    }
}

Null Coalescing Operator (??) in C#

Program Using Null Coalescing Operator ??
using System;
class Program
{
    public static void Main()
    {
        int AvailableChocolate;

        int? ChocolateForSale = null;

        AvailableChocolate = ChocolateForSale ?? 0;

        Console.WriteLine("Available Chocolate = {0}", AvailableChocolate);
    }
}

Nullable type in C#

In C# Types are divided in 2 Categories:
1. Value Types:-int, float, double,structs, enums etc
2. Reference Types:-array, class, interface, delegate etc

By default value types are non nullable data type. We use ? mark for make them nullable
int a = 0(a is non nullable , so i can't set it to null, it generate error)
int? b=0(b is nullable , so b=null is legal)

Program Using Nullable type :
using System;
class Program
{
    public static void Main()
    {
        int AvailableChocolate;

        int? ChocolateForSale = null;

        if (ChocolateForSale == null)
        {
            AvailableChocolate = 0;
        }
        else
        {
            AvailableChocolate = (int)ChocolateForSale;
        }
        Console.WriteLine("Available Chocolate = {0}",AvailableChocolate);
    }
}

Wednesday, 14 October 2015

Reverse a string using LINQ in C#

using System;
using System.Linq;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter a word for reverse in C#");
        string str = Console.ReadLine();
        string reversestring = new string(str.ToCharArray().Reverse().ToArray());
        Console.WriteLine("Reverse of entered string is : {0}",reversestring);
    }
}

Reverse a string using reverse function in C#

using System;
class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter a word for reverse");
            string str = Console.ReadLine();
            Char[] chararray = str.ToCharArray();
            Array.Reverse(chararray);
            Console.WriteLine("Reverse of entered number is {0}",chararray);
        }
    }

Reverse a number in C#

using System;
class Program
{
    public static void Main()
    {
        int num;
        int reverse = 0;
        Console.WriteLine("Please Enter a number for reverse");
        num = int.Parse(Console.ReadLine());
        while (num > 0)
        {
            int remainder = num % 10;
            reverse = (reverse * 10) + remainder;
            num = num / 10;
        }
        Console.WriteLine("Reverse of entered number is : {0}",reverse);
    }
}

Reverse a string without using function in C#

using System;
class Program
    {
        public static void Main(string[] args)
        {
            string reverse = null;
            int length;
            Console.WriteLine("Please enter a word for reverse");
            string str = Console.ReadLine();
            length = str.Length-1;
            while (length >= 0)
            {
                reverse = reverse + str[length];
                length--;
            }
            Console.WriteLine("reverse word of {0}  is : {1}", str, reverse);
        }
    }

Tuesday, 13 October 2015

Write a program in C# to check number is prime or not ?

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter a number to check its prime number or not");
        int Num = int.Parse(Console.ReadLine());

        int count = 0;

        if (Num == 0 || Num == 1)
        {
            Console.WriteLine("{0} is not a prime",Num);
        }
        else if (Num == 2)
        {
            Console.WriteLine("2 is even prime Number");
        }
        else
        {
            for (int i = 2; i <= Num/2; i++)
            {
                if (Num % i == 0)
                {
                    count++;
                    break;
                }
            }
            if (count> 0)
            {
                Console.WriteLine("{0} is not a prime number", Num);
            }
            else
            {
                Console.WriteLine("{0} is a prime number",Num);
            }
        }
    }
}

C#: Read a Number from user and Check its ODD or EVEN

using System;
class Program
{
    public static void Main()
    {
        int Num;

        Console.WriteLine("Enter a number to check its even or odd");
        Num = int.Parse(Console.ReadLine());

        if (Num > 0)
        {
            if (Num % 2 == 0)
            {
                Console.WriteLine("{0} is a even Number", Num);
            }
            else
            {
                Console.WriteLine("{0} is a odd number", Num);
            }
        }
        else
        {
            Console.WriteLine("{0} is a negative number and negative number can't be even or odd",Num);
        }
    }
}

C#: Swapping two numbers without temporary variable

using System;
class Program
{
    public static void Main()
    {
        int Num1 = 20;
        int Num2 = 33;

        Console.WriteLine("\nNumbers before swapping");
        Console.WriteLine("First Number is  : {0}", Num1);
        Console.WriteLine("Second Number is : {0}", Num2);

        Num1 = Num1 + Num2;
        Num2 = Num1 - Num2;
        Num1 = Num1 - Num2;

        Console.WriteLine("\nNumbers after swapping");
        Console.WriteLine("First Number is  : {0}",Num1);
        Console.WriteLine("Second Number is : {0}",Num2);
    }
}

C#: Swapping two numbers using third (temporary) variable

using System;
class Program
{
    public static void Main()
    {
        int Num1, Num2, temp;

        Console.WriteLine("Enter First Number");
        Num1 = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter Second Number");
        Num2 = int.Parse(Console.ReadLine());

        temp = Num1;
        Num1 = Num2;
        Num2 = temp;

        Console.WriteLine("\nNumbers after swapping");
        Console.WriteLine("First Number is  : {0}",Num1);
        Console.WriteLine("Second Number is : {0}",Num2);
    }
}