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 30, 2013
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
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
Labels:
C#
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
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
Labels:
C#
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
//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
Labels:
C#
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
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
Labels:
C#
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
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
Labels:
C#
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
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
Labels:
C#
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
//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
Labels:
C#
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
//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
Labels:
C#
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
//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
Labels:
C#
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
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
Labels:
C#
Subscribe to:
Posts (Atom)