Pages

Friday, November 29, 2013

C#: Bubble Sort

Bubble sorting is the simplest sorting algorithm. In bubble sort, we compare the consecutive pair of values in an array. Start from the beginning of the array, compare the first value with the following next value. If the first value is greater than the following value, then swap both the values. Else continue with the next consecutive pair. Continue this process for n-1 times, where n is the length of an array.

Suppose, you have an unsorted array of 5 elements
    
                             
 Here first iteration compare the first value with the second value









Now continue the iteration 4 times ie, n-1 times where n is the number of elements in an array
After 4 iterations the array will be as follows,



It's very easy to implement the above algorithm not only using C# but also in every programing languages. Here's an example program

//Method for bubble sorting
public void bubble(List<int> sort)
        {
//set a temporary variable
            int tempvar;
//Iterate through n-1 times
            for (int i = 1; i <= sort.Count; i++)
            {
//loop through each elements in all iterations
                for (int j = 0; j < sort.Count-i; j++)
                {
//compare each value with the following value,
//if greater then swap, else continue to next consecutive pair
                    if (sort[j] > sort[j + 1])
                    {
                        tempvar = sort[j];
                        sort[j] = sort[j + 1];
                        sort[j + 1] = tempvar;
                    }
                }
            }
//display sort
            display(sort);
        }

//Input array: {3,2,4,1,5}

Output:
1,2,3,4,5

Thursday, May 30, 2013

C#: Stack Implementation with and without Stack class

Stack is a datastructure which operates in Last In First Out manner(LIFO). Which means that the items that are entered last is removed first.

The program below implements stack with and without using Stack class.

Stack Implementation using Stack Class

//Declaring a Stack class
Stack<int> stk = new Stack<int>();


//Method for adding items to Stack
public void AddItems()
{
//Push method add items to Stack
stk.Push(5); // first item
stk.Push(3);
stk.Push(8); //last item
//display Stack
displaystack();
}

//Method for getting items from Stack(gets only, doesn't remove item)
public void GetItems()
{
//Peek method to get last item from Stack
Console.WriteLine("Last item in Stack: "+stk.Peek());
}

//Method to remove items from Stack
public void RemoveItems()
{

//Pop method to remove last item from Stack
stk.Pop();
//display Stack
displaystack();
}

//Method for displaying items in Stack
public void displaystack()
{
Console.WriteLine("The Stack items: ");
//loop through all items in Stack
foreach(int x in stk)
{
Console.WriteLine(x);
}

Output:
The Stack items:
5
3
8
Last item in Stack:
8
The Stack items:
5
3

Stack Implementation without using Stack class

//Declare a list for storing items
List<int> lst = new List<int>();


//Method for adding items to stack(push operation)
public void AddItems()
{
//Use Add() method to add items to Stack
lst.Add(5);
lst.Add(3);
lst.Add(8);

//display Stack
display();
}

//Method to get items from Stack(Peek operation)
public void GetItems()
{
//get item from last index
Console.WriteLine("Last value: "+lst[lst.Count - 1]);
}

//Method for removing last item from Stack(Pop operation)
public void RemoveItems()
{
//Remove last item
lst.RemoveAt(lst.Count - 1);
display();
}

Output:
The Stack Items:
5
3
8
Last value:
8
The Stack Items:
5
3

Thursday, May 23, 2013

C#: Find whether a number is power of 2

Given a number and check whether the number is a power of 2. There are different ways to find the solution, but I choose my own way to work on this.
First what I did here is find the square root of that number. Usually in C# Math.Sqrt(number), the number should be declared as double which means that number will have a decimal point ie, 4.0
After finding the square root, type cast the square root value to integer so that it removes the decimal portion completely.
If the number is power of 2, then square of type casts value will be same as the number to be checked or else the result will be false(as we removed the decimal portion of that number shows which is not power of 2).

//method for checking whether number is power of 2
 public void poweroftwo(double num)
        {
//get the square root of the number
            double val = Math.Sqrt(num);
//type cast the value to integer value
            int power = (int)val;
//check if the square of type casts value is equal to number to be checked
            if (power * power == num)
            {
                Console.WriteLine("Yes, the number is power of 2");
            }
            else
            {
                Console.WriteLine("Number not power of 2");
            }
         
       }

//Input number= 9
Output: Yes, the number is power of 2
//Input number=11
Output: Number not power of 2


Wednesday, May 22, 2013

C#: Find a number not in second array.

 Given two arrays, find the number from first array which not present in second array.


 class Program
    {
//method for dislpaying the array
        public void displayMatrix(List<int> arry)
        {
            for (int i = 0; i < arry.Count; i++)
            {
                Console.Write(arry[i] + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
        }
//method for searching a number from first array which is not present in second array
        public void ValueSearch(List<int> first, List<int> second)
        {
            List<int> distinct = new List<int>();

            for (int i = 0; i < first.Count; i++)
            {
                for (int j = 0; j < second.Count; j++)
                {
//check each value in first array is equal to any of the value in second array
                    if (first[i] == second[j])
                    {
//if any value is equal, then change that value to zero or null in first array
                        first[i] = 0;
                        break;
                    }
                }
            }
//finding the values in first array
            for (int i = 0; i < first.Count; i++)
            {
//check for values not equal to zero or null
                if (first[i] != 0)
                {
// if not equal move that value to new array.
//so that new array contain only those values which are not in second array
                    distinct.Add(first[i]);
                }
            }
            Console.Write("The numbers not in second array: ");
//display new array with values that are only in first array
            displayMatrix(distinct);
        }
        static void Main(string[] args)
        {
//Initialise two list for represting values in first array and second array
           List<int> firstArr = new List<int>();
           List<int> secndArr = new List<int>();
//add values to first array
           firstArr.Add(2);
           firstArr.Add(3);
           firstArr.Add(4);
           firstArr.Add(6);
           firstArr.Add(1);
//add values to second array
           secndArr.Add(8);
           secndArr.Add(2);
           secndArr.Add(5);
           secndArr.Add(4);
           secndArr.Add(7);

            Program pgm = new Program();
            Console.Write("The First Array: ");
//display first array
            pgm.displayMatrix(firstArr);
            Console.Write("The Second Array: ");
//display second array
            pgm.displayMatrix(secndArr);
//call the method for value search
            pgm.ValueSearch(firstArr, secndArr);
        }
    }

Output:
 
The First Array: 2  3  4  6  1
The Second Array: 8  2  5  4  7
 The numbers not in second array: 3  6  1

Monday, May 20, 2013

C#: Rotate a matrix to 90 degree.

Rotate a matrix to 90 degree. This program example works only for a matrix with number of columns equal to the number of rows.

//Matrix class
class MatrixTurn
    {
        public void DisplayMatrix(int[ ,] arry, int m, int n)
        {
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    Console.Write(arry[i, j]+" ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
        public void Degree90Matrix(int[ ,] arry, int m, int n)
        {
            int j=0;
            int p=0;
            int q=0;
            int i=m-1;
            int[,] rotatedArr = new int[m,n];

            //for (int i = m-1; i >= 0; i--)
            for(int k=0;k<m;k++)
            {
          
                while (i >= 0)
                {
                    rotatedArr[p, q] = arry[i, j];
                    q++;
                    i--;
                } 
                j++;
                i = m - 1;
                q = 0;
                p++;
           
            }
            DisplayMatrix(rotatedArr, m, n);
          
        }

        static void Main(string[] args)
        {
            int[,] arry =  { {  1, 2,3}, {  4, 5,6 },{7,8,9}  };
            Console.WriteLine("Given Matrix");
            MatrixTurn mtx = new MatrixTurn();
            mtx.DisplayMatrix(arry,3,3);

            mtx.Degree90Matrix(arry,3,3);

        }
    }


Input:
Given Matrix
1  2  3
4  5  6
7  8  9

Output Matrix:
7  4  1
8  5  2
9  6  3

Friday, May 10, 2013

C#: Swapping two numbers without temporary variable

Following program explains, how to swap two numbers without using temporary variable.
Have you ever thought of swapping to variables like so? easy to do with simple addition
and subtraction between two numbers.
//function for swapping two numbers
public void swap(int a, int b)
        {
//value of a and b before swapping
            Console.WriteLine("The value a and b before swapping: a=" + a + " and b " + b);
//if,a=3 and b=5
//a=3+5=8
//b=5
            a = a + b;
//now, b=8-5=3
//a=8, now b got a's value
            b = a - b;
//a=8-3=5
//so a=5,b=3 without using any temp var
            a = a - b;
            Console.WriteLine("The value a and b before swapping: a="+a+" and b "+b);
  }

//input: a=3, b=5
Output: a=5, b=3

Thursday, May 9, 2013

C#: Fibonacci Series

//function to display the fibonacci series
public  void  FibonacciSeries(int num)
        {
//set temporary variable
            int fibtemp= 0;
//set the first fibonacci number as 1
            int fib1 =1;
//temporary variable
            int fib2 = 0;
            Console.Write(fib1);
//loop through all the numbers
            for (int i = 0; i < num; i++)
            {
//assign temporary variable
                fib2 = fibtemp;
//save to temporary var
                fibtemp= fib1;
                //   Console.WriteLine(fib1);    
//add both temporary variables         
                fib1 = fib2 + fibtemp;

                Console.Write(" ");
                Console.Write(fib1);   
            }

       }

//input num=20 to display 20 fibonacci number series

Output:
1 1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946

Wednesday, May 8, 2013

C#: Find the duplicates

//function to display the duplicate values in an Array
public void DisplayArray(ArrayList ary)
        {
//loop through all the elements
            for (int i = 0; i < ary.Count; i++)
            {
                Console.Write(ary[i]+" ");
            }
            Console.WriteLine();
        }
//function to find the duplicate values in an Array
  public void FindDuplicate(ArrayList ary)
        {
//Array list to store all the duplicate values
           ArrayList dup = new ArrayList();
          
            for (int i = 0; i < ary.Count;i++)
            {
                for (int j =i+1; j < ary.Count; j++)
                {
//compare each value with following remaining values
                    if (ary[i].Equals(ary[j]))
                    {
//When duplicate value is found, check
//whether the value not contained in the dup array list
                        if(!dup.Contains(ary[i]))
                        {
//if not contains, then add the value to dup array list
                       dup.Add(ary[i]);
                        }
                    }
                }
            }
            Console.WriteLine("The numbers which duplicates are");
            DisplayArray(dup);
        }


//Input Arraylist values: 4,5,2,5,4,7
 Output: 4 5 2 5 4 7
               The number which duplicates are
                4 5

Tuesday, May 7, 2013

C#: Armstrong Number

An Armstrong number is the number whose sum of the cubes of the digits equal to the same number.

//function for checking the Armstrong number
 public void ArmstrongCheck(int num)
        {
//set a  variable for storing sum
            int sum = 0;
//variable for getting digit by digit of the number
            int val = 0;
//Store the variable to another 
            int ArmNum = num;
//Continue  till the number is zero
            while (num != 0)
            {
//get digit by digit using modulo
                val = num % 10;
//get the next value
                num = num / 10;
//sum of the cubes of digits
                sum += val * val * val;
            }
//sum equal to same number, then an Armstrong number
            if (sum == ArmNum)
            {
                Console.WriteLine("Armstrong Number");
            }
            else
            {
                Console.WriteLine("Not an Armstrong Number");
            }

//Input: 153
Output: Armstrong Number
//Input: 127
Output: Not an Armstrong Number

C#: Anagrams using Sort Method

Anagrams means strings having the same number of characters, but are rearranged.

//method for checking two strings are anagram
public void AnagramCheck(string str1,string str2)
{
//Remove if there are spaces in string
str1 = str1.Replace(" ","");
//Convert the string to Character Array
char[] firstStr1 = str1.ToCharArray();
str2 = str2.Replace(" ", "");
char[] secStr2 = str2.ToCharArray();

//Check whether two strings are equal length    
 if (str1.Length == str2.Length)
{
//strings with equal length
//Sort the character Array
Array.Sort(firstStr1);
Array.Sort(secStr2);


  //Loop through all elements in both character Array
  for(int i = 0; i < firstStr1.Length; i++)
  {
  //check all characters are equal in sorted char array
     if (firstStr1[i] == secStr2[i])
    {
     //Index reaches string length
    //all characters are equal
          if (i == firstStr1.Length-1)
         {
         Console.WriteLine("Anagrams");
         }
     //continue loop through all characters in the char array
     continue;
     }
    //when any character in char array not equals
   else
   {
   Console.WriteLine("Not Anagrams");
   break;
   }
  }
  }
//when two strings are not equal length
 else
 {
 Console.WriteLine("Not Anagrams");
 }
}


//Input Strings:
str1: twelve plus one
str2: eleven plus two
Output: Anagrams

str1: twelve plus one
str2: eleven pluy two
Output: Not Anagrams

Monday, May 6, 2013

C#: Matrix with value zero changes corresponding row and column to zero

Aim: Change all the value of corresponding row and column to zero, if ever the matrix contains zero as one of the elements.

//declare variable to store start index containing value zero
int[] strtIndx;
//declare variable to store end index containing value zero
int[] endIndx ;
//variables as counters to make the corresponding row
//and column zero
int m = 0;
int n = 0;

//function to display matrix
public void DisplayMatrix(int[,] ary, int p, int q)
{
//Intialise start index and end index by matrix length
strtIndx = new int[ary.Length];
endIndx = new int[ary.Length];
 //loop through two dimensional array
for (int i = 0; i < p; i++)
{
   for (int j = 0; j < q; j++)
   {
    Console.Write(ary[i, j]);
    Console.Write("  ");
    }
 Console.WriteLine();
}
}
 //function to change the corresponding row and column to zero
public void matrix(int[,] ary, int p, int q)
{
strtIndx = new int[ary.Length];
endIndx = new int[ary.Length];
//p and q represents the dimension of array
for (int i = 0; i < p; i++)
{
   for (int j = 0; j < q;j++)
   {
// Check for each value is equal to zero or not
    if (ary[i, j] == 0)
    {
//if true, store the first index to startindex
//and second index of two dimensional array to endindex
     strtIndx[m] = i;
     endIndx[n] = j;
//Increment the counter
     m++;
     n++;
     }
  }
}

//reset the value to zero
m = 0;
n = 0;
//loop through all elements and check for index equal to startindex and endindex
for (int i = 0; i < p; i++)
{
  for (int j = 0; j < q; j++)
  {
   if (i == strtIndx[m])
   {
//true, then set the value of that particular index zero
    ary[i,j]=0;
    }
     if (j == endIndx[n])
     {
      ary[i, j] = 0;
      }
    }
}    

//Input Matrix as
 { { 1, 2 }, { 3,0 }, { 5, 6 } } and dimensions as 3X2

ie,   1    2
       3    0
       5    6

Output: 1    0
              0    0
              5    0


      

Friday, May 3, 2013

C#: Palindrome

// declare and intialise a variable for storing length
int strLength = 0;
//declare and intialise a variable for represnting the first indexes of array
int intLength = 0;

//method for checking Palindrome or not  
public void CheckPalindrome(string str)
{

//get the string length
strLength = str.Length;
//Convert the string to lower case
str = str.ToLower();

//loop through all characters in string
while (intLength < strLength)
{

//check each character from first index equal to last index and
//continue through all characters in string
if (str[intLength] != str[strLength - 1])
{
//any characters not equal
Console.WriteLine("Not a Palindrome");
//quit loop
break;
}

//if characters are equal              
else
{
//increment to next index
intLength++;
//decrement string length to get last previous index
strLength--;


//if iteration completes and all characters are equal
if (intLength > strLength - 1)
{
 Console.WriteLine("Palindrome");
}

}

}

//input string: Refer
Output: Palindrome

//input string: word
Output: Not a Palindrome

Saturday, April 27, 2013

C#: Reverse a Sentence using Stack

//declare a string to store the splitted characters
string str=null;
//declare a string array to store splitted words
string[] splitStr = null;
//declare a Stack with generic integer type
Stack<string> strArr = new Stack<string>();

public void StackReversal(string s)
{
//split the words using space delimiter
splitStr=s.Split(' ');


//Iterate each character in the sentence
foreach (char ch in s)
{

//Check if character is space or it reaches the last character in the sentence.   
if (ch.Equals(' ')||s[s.Length-1]==ch)
{

//Last character in the sentence is reached
if (s[s.Length - 1] == ch)
{
//join the characters to form a string
str = str + ch;
//add the string to stack
strArr.Push(str);
//exit the loop since end of sentence
break;
}

//if not end of sentence
strArr.Push(str);
// add string to stack
strArr.Push(" ");
//for joining the next string
str = null;
}
str = str + ch;
}
//get the stack count
int c = strArr.Count;
//loop through all items in stack and display in LIFO manner
for(int i=0; i<c;i++)
{
Console.Write(strArr.Pop());
}
Console.WriteLine();
}

//input string: "This is a sentence"
Output: sentence a is This


Monday, April 8, 2013

C#: Find the largest string in an array

//declare a string as empty
string large = "";
//function to find largest string
public void FindLargest(string[] str)
{
foreach (string s in str)//for each string in string array
{
//compare the length of each string in an array
  if (s.Length > large.Length)
  {
     large = s;
   }
}
Console.WriteLine(large);
}


//for input string array as "hi","hello"
Output: hello

Thursday, April 4, 2013

C#: Decimal to Binary Conversion

public string DecToBinConvert(string deci)
{
string output = null; //declare  variable to store result
int reminderVal = 0; //declare variable to store the remainder
        
if (!IsNum(deci))// check the value to convert is numeric
{
Console.WriteLine("Not numeric!!! Enter value between 0 and 9");
}
else
{
int number = int.Parse(deci);// if numeric parse string to integer type
while (number > 0)
{
reminderVal = number % 2;//if numeric value>0, get reminder value by mod 2
number = number / 2; //get quotient value
output = reminderVal.ToString() + output;
}
}
return output;
}

private bool IsNum(string numVal)// function to check a value is numeric
{
bool answer = false;
try
{
int temp = int.Parse(numVal);
answer = true; // returns true if numeric
}
catch (Exception ex)
{
answer = false;// returns false if not numeric
}
return answer;
}

//For input value  5 convert to binary,
Output: 1010
//For input value 9.2 convert to binary,
Output: Not numeric!!! Enter value between 0 and 9

Thursday, March 28, 2013

C#: Check if one string is rotation of another string

public void StringRotate()
{
   string str = "myblogpost";  //Declare a string
   string checkstr = "tsopgolbym"; //String to be checked
   char[] charArr = new char[str.Length]; //Intialize a new char array
    int j = 0;

    if (str.Length == checkstr.Length)// if both strings are equal length
   {
    for (int i = str.Length-1; i >=0; i--) //then continue to check rotation
    {
        charArr[j] = str[i];
        j++;
    }
    string str1 = new string(charArr); // Intialize a new string
    if (str1 == checkstr)
    {
        Console.WriteLine("Both strings are rotation strings");
    }
    else
    {
        Console.WriteLine("Both strings are not a rotation strings");
    }
    }
    else // if both strings are not equal length
    {
     Console.WriteLine("Both strings are not equal length and not rotation strings");
     }
 }

Output: Both strings are rotation strings

C#: Check whether an element is present in an array and find its index?

public void ElementSearch()
{
  int[] eleArray = new int[5]{4,1,8,5,9}; // Assign values to array
  int valSearch = 5; //Search for a value
  int counter = 0; // Set a counter, if the value doesn''t exist in an array
     
  for(int i=0; i<=4; i++) //Iterate to all elements in an array
  {
    if (eleArray[i] == valSearch)// Check each value is equal to value to search
    {
       Console.WriteLine("Value found and is in index " + i + " of an array");
    }
    else //if value not found, increment the counter
    {
       counter++;
       if (counter == eleArray.Length) //counter reach arraylength, value notfound.
      {
        Console.WriteLine("Sorry! Value not found");
      }
    }
  }
}

Output: Value found and is in index 3 of an array

Sunday, March 17, 2013

C#: Using HashTable

public void HashTable()
        {
            Hashtable hash = new Hashtable();
            hash.Add("Name1", "Alex");
            hash.Add("Name2", "Peter");
      
           //Gives the value of key Name2
             Console.WriteLine(hash["Name2"].ToString());

           //Check Name1 is on list
            Console.WriteLine(hash.Contains("Name1").ToString());

            //Remove Name2 key/value and check if it still contains.
            hash.Remove("Name2");
            Console.WriteLine(hash.Contains("Name2").ToString());

            try
            {
               //To display an item already removed from list and catched by exception.
                Console.WriteLine(hash["Name2"].ToString());
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("The key value missing");
            }

           //Add two more value to list
            hash.Add("Name2", "Sam");
            hash.Add("Name3", "Kite");
          
           //To iterates the items in hashtable.
            IDictionaryEnumerator enumr=hash.GetEnumerator();
            while (enumr.MoveNext())
            {
                Console.WriteLine(enumr.Key.ToString());
            }
        }

Output:Peter
            True
            False
            The key value missing
            Name1
            Name2
            Name3

C#: Replace a String

public void ReplaceString()
{
   string str = "Hello how are you!";
   string result= str.Replace(" ","--");
   Console.WriteLine(result);
}

Output: Hello--how--are--you!

C#: Display Random String

public void RandomString()
{
 string[] randStr = new string[5]{"hi","hello","how","are","you"};
 int indexStr = rnd.Next(randStr.Length);
 Console.WriteLine(randStr[indexStr]);
}

Output: hello

C#: Display Random Numbers

public void RandomNumber()
 {
 Random rnd = new Random();
int[] randArray = new int[10];
 int rand1 ;
for (int i = 0; i < 10; i++)
{
 rand1 = rnd.Next(1, 10); // Random numbers between 1 and 10
 Console.WriteLine(rand1);
 }
}

Output: 8
              2
              6
              4
              5
              7
              6
              3
              3
              2
              


Saturday, March 16, 2013

C#: Check whether a string is substring of another string?


public void CheckForSubstring()
        {
            string str = "onetwothree";
            bool result = str.Contains("two");
            Console.WriteLine(result);  //returns True

            result = str.Contains("Two"); //returns False, bcoz C# is case sensitive
            Console.WriteLine(result);
        }

Output: True
              False  

C#: String Reversal

 public void StringReverse()
        {
           string str = "stringtoberevered";

            char[] chararr = new char[str.Length];

            chararr = str.ToCharArray();
            Console.Write("The Reversed String = ");
            for (int i = str.Length - 1; i >= 0; i--)
            {

                Console.Write(chararr[i]);

            }
            Console.WriteLine();
        }

Output: dereverebotgnirts

C#: How to find minimum value from an array of integers?

  public void MinimumValInt()
        {
            int[] intArray = new int[7] { 10,4,5,1,7,15,12};
            int minVal = intArray[0];

            for (int i = 1; i < intArray.Length; i++)
            {
                if (intArray[i] < minVal)
                {
                    minVal = intArray[i];
                }
            }
            Console.WriteLine("Minimum value= "+minVal);
        }


Output: Minimum value=1