Consolatedapp
Consolatedapp
1. Given two strings. U has to find the second string as a substring of first st
ring. If the string
is found as substring of first string then return the index where it started in
the first string
otherwise return -1.
Input: Internet and search string is net . Out put:5
//With Functions
public static void Main()
{
string mainStr = Console.ReadLine();
string subStr = Console.ReadLine();
for (int i = 0; i <= mainStr.Length - subStr.Length; i++)
{
if (mainStr.Substring(i, subStr.Length).Equals(subStr))
Console.WriteLine(i.ToString());
}
Console.ReadLine();
}
//Without Function
public static void Main()
{
string mainStr = Console.ReadLine();
string subStr = Console.ReadLine();
for (int i = 0; i <= mainStr.Length - subStr.Length; i++)
{
bool flag = true;
for (int j = 0; j < subStr.Length; j++)
{
if (mainStr[i + j] == subStr[j])
{
flag = flag && true;
}
else
{
flag = flag && false;
}
}
if (flag)
{
Console.WriteLine(i.ToString());
}
}
Console.ReadLine();
}
2. Find 2nd Maximum Number in an array?
public static void Main()
{
int[] ar = { 31, -41, 26, 59, -53, 58, 97, -93, -23, 84 };
int max1 = 0, max2 = 0;
for (int i = 0; i < ar.Length; i++)
{
if (ar[i] > max1 && max2 <=max1)
{
max2 = max1;
max1 = ar[i];
}
else if(ar[i]>max2)
{
max2 = ar[i];
}
}
Console.WriteLine("First Max
in array", max1, max2);
}
3. Find 3rd max in an array?
: {0} and Second max in array : {1}
public static void Main(string[] args)
{
int s=0, l=0, m=0;
int[] ar ={ 12, 3, 34, 5, 3, 0, 19, 19 };
for (int i = 0; i < ar.Length; i++)
{
if (l < ar[i] && m <= l)
{
s = m;
m = l;
l = ar[i];
}
else if (m < ar[i] && s <= m)
{
s = m;
m = ar[i];
}
else if (s <= ar[i])
{
s = ar[i];
}
}
}
4. Finding max sub series sum in an given array?
public static void Main()
{
int[] ar = { 31, -41, 26, 59, -53, 58, 97, -93, -23, 84 };
int startIndex = 0, endIndex = 0, maxTillHere = 0, maxSoOn = 0,
countStart = -1;
for (int i = 0; i < ar.Length; i++)
{
if (maxTillHere + ar[i] > 0)
{
maxTillHere += ar[i];
countStart++;
}
else
{
maxTillHere = 0;
countStart = -1;
}
if (maxSoOn < maxTillHere)
{
maxSoOn = maxTillHere;
endIndex = i;
startIndex = endIndex - countStart;
}
}
Console.WriteLine("Sum of max Series : " + maxSoOn + "\nStart
index : {0} and End index : {1} in array" , startIndex , endIndex);
}
5. Write a function to reverse a string.
public static void Main()
{
string str = Console.ReadLine();
char[] str1 = str.ToCharArray();
for (int j = 0; j < str1.Length / 2; j++)
{
char temp;
temp = str1[j];
str1[j] = str1[str1.Length - j - 1];
str1[str1.Length - j - 1] = temp;
}
for (int i = 0; i < str1.Length; i++)
Console.Write(str1[i]);
Console.ReadLine();
}
6. Find the duplicate in a given string and return the string without duplicates
.
public static void Main()
{
int k = 1;
string str = Console.ReadLine();
char[] str1 = str.ToCharArray();
for (int j = 1; j < str1.Length; j++)
{
bool flag = false;
for(int i=j-1;i>=0;i--)
{
if(!flag && str1[i]==str1[j])
flag=true;
}
if (!flag)
{
str1[k] = str1[j];
k += 1;
}
}
for (int i = 0; i < k; i++)
Console.Write(str1[i]);
Console.ReadLine();
}
7. Take an array of n and it contains 1 to n except one number, find that missin
g number.
static void Main(string[] args)
{
int[] a={1,2,2,3,4,5,6,7,8,9};
int n=a.Length-1;
int sum1=(n*(n+1))/2;
int sum2=0;
for(int i=0;i<=n;i++)
sum2=sum2+a[i];
int x=sum1-sum2;
int y = sum2 % 5;
Console.WriteLine("Missing element is"+ (x + y));
}
8. Write the code for displaying the elements of a 4 by 4 matrix by moving spira
lly.
public static void Main()
{
Console.WriteLine("Enter matrix size");
int m = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[m, m];
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
matrix[i, j] = Convert.ToInt32(Console.ReadLine());
for (int i = m - 1, j = 0; i > 0; i--, j++)
{
for (int k = j; k < i; k++)
Console.WriteLine(matrix[j, k].ToString());
for (int k = j; k < i; k++)
Console.WriteLine(matrix[k, i].ToString());
for (int k = i; k > j; k--)
Console.WriteLine(matrix[i, k].ToString());
for (int k = i; k > j; k--)
Console.WriteLine(matrix[k, j].ToString());
}
9. Write code in C# for the below function, and tell how many times this functio
n would be
called when 5 is passed to it. There is a function.
F(x) = f(x-1) + f(x-2) when x>1;
F(x) = 1 when x<=1;
int fib(int n)
if (n <= 2) return 1;
else return fib(n-1) + fib(n-2);
10. A file was given contains some numbers asked to display all thos numbers in
sorted order.
The numbers range from 1 to 2000 and they are placed line by line.
Time complexity- O(n)
File should be created at c:\temp\read.txt
Here I have used Bubble sort method to sort the elements. We can use Selection s
ort,
Insertion Sort or Quick sort to sort the array.
class FileSorted
{
static void Main(string[] args)
{
FileStream fs = new FileStream(@"c:\temp\read.txt",
FileMode.Open, FileAccess.Read);
int[] a = new int[10];
int i = 0;
StreamReader sr = new StreamReader(fs);
while (sr.Peek() >= 0)
{
a[i] = Int32.Parse(sr.ReadLine());
i++;
}
int n = a.Length;
try
{
for (int k = 1; k <= n - 1; k++)
{
int ptr = 0;
while (ptr < n - k)
{
if (a[ptr] > a[ptr + 1])
{
int s = a[ptr];
a[ptr] = a[ptr + 1];
a[ptr + 1] = s;
}
ptr = ptr + 1;
}
}
for (int j = 0; j < n; j++)
Console.Write(a[j].ToString() + ", ");
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
}
11. Write Code for binary search algorithm. If u pass unsorted array to it will
it work?
static void Main(string[] args)
{
Console.WriteLine("Enter Item Value to search(1 to 9)");
int item = Int32.Parse(Console.ReadLine());
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int begin = 0;
int end = a.Length - 1;
int mid = (int)((begin + end) / 2);
while (a[mid] != item && begin <= end)
{
if (item > a[mid])
{
begin = mid + 1;
}
else
{
end = mid - 1;
}
mid = (int)((begin + end) / 2);
}
if (a[mid] == item)
{
Console.Write(mid.ToString());
}
else
{
Console.Write("Item Not found");
}
}
12. Write a C# / C / C++ program to insert a new element in sorted array? (Hint:
Using binary
search technique). Write a sample inputs where the program fails.
static void Main(string[] args)
{
Console.WriteLine("Enter lengh of array in list");
int arLength = Int32.Parse(Console.ReadLine());
ArrayList a = new ArrayList();
for (int i = 0; i < arLength; i++)
{
a.Add(Convert.ToInt32(Console.ReadLine()));
}
Console.WriteLine("Enter Item to insert in list");
int item = Int32.Parse(Console.ReadLine());
int begin = 0;
int end = arLength - 1;
int mid = (begin + end) / 2;
bool flag1 = false, flag2 = false;
if(item<Convert.ToInt32(a[0]))
{
a.Insert(0, item);
}
else if (item > Convert.ToInt32(arLength-1))
{
a.Insert(arLength, item);
}
else
{
while (!(flag1 && flag2))
{
if (item >= Convert.ToInt32(a[mid]))
{
flag1 = true;
begin = mid + 1;
}
else if (Convert.ToInt32(a[arLength - 1]) < item)
{
flag2 = true;
}
else
{
flag2 = true;
end = mid - 1;
}
mid = (begin + end) / 2;
}
a.Insert(mid + 1, item);
}
If you are using array do following
We can write Customized code in C# to increase the size of the array during run
time as follows
Write a function which takes an array as an argument and copies the content into
another array
and returns the copied array
public Array Redim(Array arrToResize, int length)
{
Type t= arrToResize.GetType().GetElementType();
Array newArray=Array.CreateInstance(t,length);
Array.Copy(arrToResize,0,newArray,0,Math.Min(arrToResize.Length,length));
return newArray;
}
13. Write function to check whether a number having repeated digits or not.. Wit
h O(n). Write
sample inputs where the above program will fails.
static void Main(string[] args)
{
string str = Console.ReadLine();
char[] ch = str.ToCharArray();
int[] iAr=new int[10];
for (int i = 0; i < ch.Length; i++)
{
iAr[Convert.ToInt32(ch[i] - '0')] = iAr[Convert.ToInt32(ch[i] - '0')] +
1;
}
}
14. There is an array consisting of Values R, G, B in a random order. We have to
move all R s
left side and all B s right side and we have to place all G s in the middle. Find th
e solution
Write Test cases for above
static void Main(string[] args)
{
string[] a = { "R", "G", "B", "R", "G",
"B","R","R","B","G","B","G" };
int n = a.Length/3;
for(int i = 0; i < n; i++)
{
a[i] = "R";
a[i + n] = "G";
a[i+2*n] = "B";
}
for(int j=0;j<a.Length;j++)
Console.WriteLine(a[j].ToString());
Console.Read();
static void Main(string[] args)
{
int l = 0, j = 0, k = 0;
char[] a = { 'R', 'G', 'B', 'R', 'G', 'B', 'R', 'R', 'B',
'G', 'B', 'G' };
for (int i = 0; i < a.Length; i++)
{
if (a[i] == 'R')
l++;
else if (a[i] == 'G')
j++;
else
k++;
}
Console.WriteLine(l + " " + j + " " + k);
Console.Read();
}
15. Write a function which compacts a sorted array.
- Array is sorted in ascending order
- Compact means removing the
duplicates
function along with signature
Write as many test cases as you can for the above function
- Final output should be in the same array given
- Optimal in time and memory
static void Main(string[] args)
{
int[] a ={ 1, 6, 1, 4, 5, 1, 3 };
int[] b = new int[10];
for (int i = 0; i < a.Length; i++)
b[a[i]] = b[a[i]] + 1;
for (int i = 0; i < b.Length; i++)
if (b[i] >= 1)
Console.WriteLine(i.ToString());
Console.ReadLine();
}
16. Write a program which would reverse a sentence. Test cases for the program.
static void Main(string[] args)
{
string str = "the world will go on forever";
string[] sArray= str.Split(' ');
str = null;
for(int i=sArray.Length-1;i>=0;i--)
str+=sArray[i]+" ";
Console.WriteLine("\n"+str);
}
static void Main(string[] args)
{
string strSupplied = "how are you";
string strWord = null;
string strResult = null;
for (int i = strSupplied.Length - 1; i >= 0; i--)
{
if (strSupplied[i].ToString() != " ")
strWord = strSupplied[i] + strWord;
else
{
strResult = strResult + " " + strWord;
strWord = "";
}
}
strResult = strResult + " " + strWord;
Console.Write(strResult.ToString());
Console.ReadKey();
}
17. Write an algorithm for the following function
a. A Function having two arguments.
b. First argument is a string
c. Second argument is integer value NRP ( No. Of RePetitions)
d. The function should print the characters which repeats NPR times
I/P:
ABDCFNABFASDFJDL , 3
O/P:
A, D, F
public void NumOfReps(string s, int nrp)
{
string str = s;
char[] a = str.ToCharArray();
int rep = nrp;
int n = a.Length;
try
{
for (int i = 1; i <= n - 1; i++)
{
int count = 0;
for (int j = 0; j <= i; j++)
{
if (a[i] == a[j])
{
count++;
}
}
if (count == rep)
{
Console.Write(a[i]);
}
}
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
}
static void Main(string[] args)
{
string str = "DDDCFNABFASDFJDL";
Hashtable t = new Hashtable();
for (int i = 0; i < str.Length; i++)
{
if (t.ContainsKey(Convert.ToChar(str[i])))
t[Convert.ToChar(str[i])] = Convert.ToInt32(t[Convert.ToChar(str[i])]
== null ? 1 : Convert.ToInt32(t[Convert.ToChar(str[i])]) + 1);
else
t.Add(Convert.ToChar(str[i]), Convert.ToInt32(t[Convert.ToChar(str[i])]
== null ? 1 : Convert.ToInt32(t[Convert.ToChar(str[i])]) + 1));
}
}
18. Program to Convert Numeric String to Float
static void Main(string[] args)
{
string str1= 123.345 ;
char [] str=str1.ToCharArray();
float num=0;
int flag=0,count=1;
for (int i=0;i<str.Length; i++)
{
if(str[i]=='.') flag=1;
else
{
num=(float)(num*10)+((str[i])-'0');
if(flag==1)count*=10;
}
}
num = num/count;
Console.WriteLine(num);
}
19. Program to Convert Int to String
static void Main(string[] args)
{
int x = 123, y;
string str = null;
while (x > 0)
{
y = x % 10;
str = str + y.ToString();
x = x / 10;
}
Console.WriteLine(str);
}
20. Checking for Palindrome
void palind(string str1)
{
bool flag=true;
for (int i=0;i<str1.Length/2;i++)
{
if(str1[i]!=str1[str1.Length-i-1])
{
flag=false;
break;
}
}
if(flag)
Console.WriteLine("\nstring is palindrome\n");
else
Console.WriteLine("\nNot palind\n");
}
public class palindram
{
public static void Main(string[] args)
{
int y,s=0,z;
string st1=Console.In.ReadLine();
int x = Convert.ToInt32(st1);
z = x;
while (x != 0)
{
y = x % 10;
x = x / 10;
s = s * 10 + y;
}
if (s == z)
Console.WriteLine("Palindram");
else
Console.WriteLine("Not a palindram");
}
19. Sorting the string
void strSort(char[] str)
{
char sTemp;
bool flag;
for(int i=0;i<str.Length;i++)
{
flag=false;
for(int j=0;j<str.Length-1;j++)
{
if(str[j]>str[j+1])
{
sTemp =str[j];
str[j]=str[j+1];
str[j+1]=sTemp;
flag=true;
}
}
if(!flag) break;
}
for(int i=0;i<str.Length;i++)
Console.Write(str[i]);
21. Write a program to get LCM and GCD of given 2 numbers?
static void Main(string[] args)
{
Console.WriteLine("Enter the String");
int i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the String");
int j = Convert.ToInt32(Console.ReadLine());
int k = i * j;
while (i > 0)
{
if (i < j)
{
if (j % i == 0)//i % j == 0 ||
{
Console.WriteLine("GCD ="+i.ToString());
break;
}
else
j = j % i;
}
else
{
i = i + j;
j = i - j;
i = i - j;
}
}
Console.WriteLine("LCM ="+k/i);
Console.ReadLine();
}
22. Swapping of 2 number without using 3rd variable
class Interchange
{
static void Main(string[] args)
{
int x = 12, y=20;
Console.WriteLine("x::::" + x);
Console.WriteLine("y::::" + y+"\n\n");
x = x + y;
y = x - y;
x = x - y;
Console.WriteLine("x::::"+x );
Console.WriteLine( "y::::" + y);
}
}
23. Program for Fibonacci series.
class Fibonacci
{
static void Main(string[] args)
{
int x = 0, y = 1,s;
Console.Write(x + "\t" + y + "\t");
for (int i = 0; i < 20; i++)
{
s = x + y;
x = y;
y = s;
Console.Write(s + "\t");
}
}
}
24. Sorting Array with 0 s and 1 s
static void Main(string[] args)
{
int k = 0;
int[] a = { 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 };
for (int i = 0; i < a.Length ; i++)
{
if (a[i] == 0)
{
int temp = a[k];
a[k] = a[i];
a[i] = temp;
k++;
}
}
Console.Read();
}
24. Finding duplicate element in array[100] which contain 1 to 99 and one duplic
ate.
class Class1
{
static void Main(string[] args)
{
int[] a={1,2,2,3,4,5,6,7,8,9};
int n=a.Length-1;
int sum1=(n*(n+1))/2;
int sum2=0;
for(int i=0;i<=n;i++)
sum2=sum2+a[i];
int x=sum2-sum1;
Console.WriteLine("Duplicate element is"+x.ToString());
}
25. Write a program to find angle between two hands of a clock
class Time_Angle
{
static void Main(string[] args)
{
int m, h;
float angle;
Console.WriteLine("Enter the string in hh:mm");
string time = Console.In.ReadLine();
string[] split = time.Split(':');
try
{
h = Convert.ToInt32(split[0]);
m = Convert.ToInt32(split[1]);
if ((h >= 0 && h <= 12) && (m >= 0 && m <= 60))
{
angle = Mod(h * 360 / 12 - m * 11 / 2);
if (angle > 180)
angle = 360 - angle;
Console.WriteLine("angle b/w hours and mins==" +
angle);
}
}
catch
{
Console.WriteLine("enter date in correct format");
}
}
private static float Mod(float p)
{
if (p < 0)
return -1 * p;
else
return p;
}
26. Count set bits in a given number.
class Program
{
static void Main(string[] args)
{
int n = 7;
int count = 0;
while (n > 0)
{
count += n & 1;
n = n >> 1;
}
Console.WriteLine(count);
Console.ReadLine();
}
}
27. Program to shuffle deck of cards
using System;
using System.Collections.Generic;
using System.Text;
namespace Shuffling
{
public enum Suit
{
Clubs, Hearts, Spades, Diamonds
}
public enum Rank
{
Ace, Duece, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King
}
public class Card
{
public Suit m_suit = 0;
public Rank m_rank = 0;
public Card() { }
public Card(Rank rank, Suit suit)
{
m_rank = rank;
m_suit = suit;
}
public override string ToString()
{
return "The " + m_rank + " of " + m_suit;
}
}
public class Deck
{
public Card[] card;
public Deck()
{
card = new Card[52];
}
public void Shuffle()
{
bool[] bAssigned = new bool[52];
for (int iRank = 0; iRank < 13; iRank++)
{
for (int iSuit = 0; iSuit < 4; iSuit++)
{
Random randomCard = new Random();
bool bCardFound = false;
while (bCardFound == false)
{
int index = randomCard.Next(52);
if (bAssigned[index] == false)
{
card[index] = new Card((Rank)iRank, (Suit)
iSuit);
bCardFound = true;
bAssigned[index] = true;
Console.WriteLine(card[index].ToString());
}
}
}
}
}
}
class Shuffle
{
static void Main(string[] args)
{
Console.WriteLine("Enter how many times u want to
shuffle?");
string nooftimes = Console.ReadLine();
int n = Convert.ToInt32(nooftimes, 10);
if (n > 0)
{
Deck deck = new Deck();
for (int i = 0; i < n; i++)
{
Console.WriteLine("\nThe orders cards after " + (i
+ 1).ToString() + " shuffling :\n");
deck.Shuffle();
}
}
Console.ReadLine();
}
}
}
28. Write a function that accepts two parameters (date, integer number). It shou
ld return the
date after adding the integer number of days. It s similar to the adddays() functi
on in .Net.
System;
System.Collections;
System.Text;
System.Globalization;
namespace ConsoleApplication2
{
class Program
{
public static void Main(string[] args)
{
Program a = new Program();
Console.Write("Enter days to add or remove :");
int days =Convert.ToInt32(Console.ReadLine());
string date = a.AddDay(DateTime.Now, days);
Console.WriteLine(date);
date = DateTime.Now.AddDays(days).ToString("d MM yyyy");
Console.WriteLine(date);
Console.ReadKey();
}
private bool CheckLeapYear(int year)
{
bool leapYear = false;
leapYear = (((year % 4) == 0) && ((year % 100) != 0) ||
((year % 400) == 0));
if (leapYear.Equals(true))
return true;
else
return false;
}
private string AddDay(DateTime dateTime, int p)
{
Program a = new Program();
int totalDays = 0;
int daysTillMonth;
int daysTillDate;
string date = dateTime.ToString("d MM yyyy HH:mm:ss.f");
string[] str = date.Split(' ');
int day = Convert.ToInt32(str[0]);
int year = Convert.ToInt32(str[2]);
int month = Convert.ToInt32(str[1]);
int aYear=0;
bool bYear = a.CheckLeapYear(year);
byte leapDay = 0;
if (bYear)
{
totalDays = 366;
leapDay = 1;
}
else
totalDays = 365;
daysTillMonth = a.DaysTillMonth(month - 1, leapDay);
daysTillDate = daysTillMonth + day + p;
//For year
if (daysTillDate > totalDays)
{
aYear = year + (daysTillDate / totalDays);
daysTillDate = daysTillDate % totalDays;
}
else if (daysTillDate <= 0)
{
aYear = year + (daysTillDate / totalDays)-1;
daysTillDate = totalDays + (daysTillDate % totalDays);
}
int leapDayYears=0;
if (year > aYear)
{
for (int i = year; year >= aYear; year--)
{
if (a.CheckLeapYear(year))
leapDayYears++;
}
}
else
{
for (int i = year; year <= aYear; year++)
{
if (a.CheckLeapYear(year))
leapDayYears--;
}
}
int[] dayMonth = a.DayMonth(daysTillDate + leapDayYears,
leapDay);
return dayMonth[0] + " " + dayMonth[1] + " " + aYear;
}
private int[] DayMonth(int daysTillDate, int leapDay)
{
int[] dayMonth = new int[2];
if (0 < daysTillDate && daysTillDate <= 31)
{
dayMonth[0] = daysTillDate;
dayMonth[1] = 1;
return dayMonth;
}
else if (31 < daysTillDate && daysTillDate <= 59 + leapDay)
{
dayMonth[0] = daysTillDate - 31;
dayMonth[1] = 2;
return dayMonth;
}
else if (59 + leapDay < daysTillDate && daysTillDate <= 90
+ leapDay)
+ leapDay)
{
dayMonth[0] = daysTillDate - 59 + leapDay;
dayMonth[1] = 3;
return dayMonth;
}
else if (90 + leapDay < daysTillDate && daysTillDate <= 120
{
dayMonth[0] = daysTillDate - 90 + leapDay;
dayMonth[1] = 4;
return dayMonth;
}
else if (120 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 120 + leapDay;
dayMonth[1] = 5;
return dayMonth;
}
else if (151 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 151 + leapDay;
dayMonth[1] = 6;
return dayMonth;
}
else if (181 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 181 + leapDay;
dayMonth[1] = 7;
return dayMonth;
}
else if (212 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 212 + leapDay;
dayMonth[1] = 8;
return dayMonth;
}
else if (243 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 243 + leapDay;
dayMonth[1] = 9;
return dayMonth;
}
else if (273 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 273 + leapDay;
dayMonth[1] = 10;
return dayMonth;
}
else if (304 + leapDay < daysTillDate && daysTillDate
+ leapDay)
{
dayMonth[0] = daysTillDate - 304 + leapDay;
dayMonth[1] = 11;
return dayMonth;
}
else if (334 + leapDay < daysTillDate && daysTillDate <=
365 + leapDay)
{
dayMonth[0] = daysTillDate - 334 + leapDay;
dayMonth[1] = 12;
return dayMonth;
}
else
{
dayMonth[0] = 0;
dayMonth[1] = 0;
return dayMonth;
}
}
private int DaysTillMonth(int month, int leapDay)
{
switch (month)
{
case 1:
return 31;
case 2:
return 59 + leapDay;
case 3:
return 90 + leapDay;
case 4:
return 120 + leapDay;
case 5:
return 151 + leapDay;
case 6:
return 181 + leapDay;
case 7:
return 212 + leapDay;
case 8:
return 243 + leapDay;
case 9:
return 273 + leapDay;
case 10:
return 304 + leapDay;
case 11:
return 334 + leapDay;
case 12:
return 365 + leapDay;
default:
return 0;
}
}
29. Construction of single linked list
1. Insertion at Starting
2. Insertion at any Position
3. Insertion at Ending
4. Deletion at Starting
5. Deletion at Ending
6. Deletion at any Position
7. Sorting the List
8. Reverse the List
9. Traverse the List
10. Find Middle of the List
using System;
using System.Collections.Generic;
using System.Text;
namespace Applications
{
class ListNode
{
int data;
ListNode next;
public ListNode()
{
data = 0;
next = null;
}
public void Read()
{
data = int.Parse(Console.ReadLine());
}
public void Print()
{
Console.Write("\t" + data + " --->");
}
public int Data
{
get
{
return data;
}
set
{
data = value;
}
}
public ListNode Next
{
get
{
return next;
}
set
{
next = value;
}
}
class LinkList
{
ListNode Head;
public LinkList()
{
Head = null;
}
public void Design()
{
Console.WriteLine("\n\n**** Single Linked List ****");
Console.WriteLine("**** Select one from the below
Choices****");
Console.WriteLine("1. Insertion at Starting ");
Console.WriteLine("2. Insertion at any Position ");
Console.WriteLine("3. Insertion at Ending ");
Console.WriteLine("4. Deletion at Starting ");
Console.WriteLine("5. Deletion at Ending ");
Console.WriteLine("6. Deletion at any Position ");
Console.WriteLine("7. Sorting the List ");
Console.WriteLine("8. Reverse the List ");
Console.WriteLine("9. Traverse the List ");
Console.WriteLine("10. Find Middle of the List");
Console.WriteLine("11. Exit ");
}
public void Create(int n)
{
if (n == 0)
Head = null;
else
{
int k = 0;
Head = new ListNode();
Console.Write("Enter the Node " + (k + 1) + ":");
Head.Read();
ListNode temp = Head;
for (k = 1; k < n; k++)
{
Console.Write("Enter the Node " + (k + 1) + ":");
temp.Next = new ListNode();
temp = temp.Next;
temp.Read();
}
}
}
public void Traverse()
{
if (Head == null)
return;
ListNode ptr = Head;
Console.WriteLine("\nThe Elements are ");
while (ptr != null)
{
ptr.Print();
ptr = ptr.Next;
}
Console.WriteLine();
}
public void InStart()
{
ListNode Temp = new ListNode();
Console.WriteLine("Enter the Value of Node");
Temp.Read();
Temp.Next = Head;
Head = Temp;
}
public void InEnd()
{
ListNode Temp = new ListNode();
Console.WriteLine("Enter the Value of Node");
Temp.Read();
if (Head == null)
{
Head = Temp;
}
else
{
ListNode ptr = Head;
while (ptr.Next != null)
{
ptr = ptr.Next;
}
ptr.Next = Temp;
}
}
public void inMid(int pos)
{
ListNode Temp = new ListNode();
Console.WriteLine("Enter the Value of Node");
Temp.Read();
ListNode ptr = Head;
ListNode x = null;
if (pos == 1)
{
Temp.Next = ptr;
Head = Temp ;
}
else
{
for (int i = 1; i < pos; i++)
{
x = ptr;
ptr = ptr.Next;
}
x.Next = Temp;
Temp.Next = ptr;
}
}
public void delStart()
{
ListNode Temp = Head;
Head = Temp.Next;
}
public void delMid(int pos)
{
int i = 1;
ListNode ptr = Head;
ListNode x = null;
if (pos == 1)
{
Head = ptr.Next;
}
else
{
while (i < pos)
{
x = ptr;
ptr = ptr.Next;
i++;
}
x.Next = ptr.Next;
}
}
public void delEnd()
{
ListNode ptr = Head, x = null;
while (ptr.Next != null)
{
x = ptr;
ptr = ptr.Next;
}
x.Next = null;
}
public void Reverse()
{
ListNode Result = null;
ListNode PNext;
ListNode Current = Head;
while (Current != null)
{
PNext = Current.Next;
Current.Next = Result;
Result = Current;
Current = PNext;
}
Head = Result;
}
public void Sorting()
{
if (Head == null)
return;
ListNode NodeI, NodeJ;
int temp = 0;
for (NodeI = Head; NodeI != null; NodeI = NodeI.Next)
{
for (NodeJ = NodeI.Next; NodeJ != null; NodeJ =
NodeJ.Next)
{
if (NodeI.Data > NodeJ.Data)
{
temp = NodeJ.Data;
NodeJ.Data = NodeI.Data;
NodeI.Data = temp;
}
}
}
}
public void FindMid()
{
ListNode p = Head;
ListNode q = Head;
if (q.Next != null)
{
while ((q.Next != null) && (q.Next.Next != null))
{
p = p.Next;
q = q.Next.Next;
}
if (q.Next != null)
Console.WriteLine("The Middle Node are " + p.Data
+ " and " + p.Next.Data);
else
Console.WriteLine("The Middle Node is " + p.Data);
}
else
Console.WriteLine("There is only one Node ie " +
q.Data);
}
}
class SingleLinked
{
static void Main(string[] args)
{
LinkList li = new LinkList();
Console.Write("Enter the No. of Nodes:");
int n = int.Parse(Console.ReadLine());
li.Create(n);
li.Traverse();
li.Design();
bool flag = true;
while (flag)
{
Console.WriteLine("Enter your choose");
Insert: ");
Delete: ");
int ch = int.Parse(Console.ReadLine());
switch (ch)
{
case 1:
li.InStart();
li.Traverse();
break;
case 2:
Console.Write("Enter the Position U want to
int pos = int.Parse(Console.ReadLine());
li.inMid(pos);
li.Traverse();
break;
case 3:
li.InEnd();
li.Traverse();
break;
case 4:
li.delStart();
li.Traverse();
break;
case 5:
li.delEnd();
li.Traverse();
break;
case 6:
Console.Write("Enter the Position U want to
pos = int.Parse(Console.ReadLine());
li.delMid(pos);
li.Traverse();
break;
case 7:
li.Sorting();
li.Traverse();
break;
case 8:
li.Reverse();
li.Traverse();
break;
case 9:
li.Traverse();
break;
case 10:
li.FindMid();
break;
default:
flag = false;
break;
}
}
Console.ReadLine();
}
30. Construct of linked list using c# inbuilt function s.
class List
{
private string _comment;
private string _num;
public List(string num, string comment)
{
_comment = comment;
_num = num;
}
public string num
{
get { return (_num); }
set { _num = value ; }
}
public string comment
{
get { return (_comment); }
set { _comment = value; }
}
}
class linklist
{
static void Main()
{
LinkedList<List> l1 = new LinkedList<List>();
List n1 = new List("4", "It comes last");
List n2 = new List("3", "It comes before last");
List n3 = new List("2", "It comes after first");
List n4 = new List("1", "It comes first");
Console.WriteLine("this");
l1.AddLast(n1);
LinkedListNode<List> node = l1.FindLast(n1);
l1.AddBefore(node, n3);
l1.AddBefore(node, n2);
l1.AddFirst(n4);
l1.Remove(n3);
foreach (List x in l1)
{
Console.WriteLine(x.num + "::::" + x.comment);
}
}
31. Construction of circular Linked List
using System;
using System.Collections.Generic;
using System.Text;
namespace Applications
{
class CircularListNode
int data;
CircularListNode right;
public CircularListNode()
{
data = 0;
right = null;
}
public CircularListNode Right
{
get
{
return right;
}
set
{
right = value;
}
}
public void Read()
{
data = int.Parse(Console.ReadLine());
}
class CircularLinkList
{
CircularListNode Head;
public CircularLinkList()
{
Head = null;
}
public void Create(int n)
{
if (n == 0)
Head = null;
else
{
int k = 0;
Head = new CircularListNode();
Console.Write("Enter the Node " + (k + 1) + ":");
Head.Read();
CircularListNode temp = Head;
for (k = 1; k < n; k++)
{
Console.Write("Enter the Node " + (k + 1) + ":");
temp.Right = new CircularListNode();
temp = temp.Right;
temp.Read();
temp.Right = Head;
}
}
}
class Circular_List
static void Main(string[] args)
{
CircularLinkList li = new CircularLinkList();
Console.Write("Enter the No. of Nodes:");
int n = int.Parse(Console.ReadLine());
li.Create(n);
}
32. Construction of doubly linked list
using System;
using System.Collections.Generic;
using System.Text;
namespace Applications
{
class DoubleListNode
{
int data;
DoubleListNode left;
DoubleListNode right;
public DoubleListNode()
{
data = 0;
left = null;
right = null;
}
public DoubleListNode Left
{
get
{
return left;
}
set
{
left = value;
}
}
public DoubleListNode Right
{
get
{
return right;
}
set
{
right = value;
}
}
public void Read()
{
data = int.Parse(Console.ReadLine());
}
class DoubleLinkList
{
DoubleListNode Head;
public DoubleLinkList()
{
Head = null;
}
public void Create(int n)
{
if (n == 0)
Head = null;
else
{
int k = 0;
Head = new DoubleListNode();
Console.Write("Enter the Node " + (k + 1) + ":");
Head.Read();
DoubleListNode temp = Head;
for (k = 1; k < n; k++)
{
Console.Write("Enter the Node " + (k + 1) + ":");
temp.Right = new DoubleListNode();
temp.Right.Left = temp;
temp.Right.Read();
temp = temp.Right;
}
}
}
class Double_Linked
{
static void Main(string[] args)
{
DoubleLinkList li = new DoubleLinkList();
Console.Write("Enter the No. of Nodes:");
int n = int.Parse(Console.ReadLine());
li.Create(n);
}
}
33. Stack program using C#.
public class Stack_Program
{
private static ArrayList jobs = new ArrayList();
private static int nextJobPos = 0;
private static int index = 0;
public static void AddJob(string jobName)
{
jobs.Insert(index - nextJobPos, jobName);
index++;
}
public static string GetNextJob()
{
if (jobs.Count == nextJobPos)
return "NO JOBS IN BUFFER";
else
{
string jobName = Convert.ToString(jobs[jobs.Count-1-
nextJobPos]);
nextJobPos++;
return jobName;
}
}
public static void Main()
{
AddJob("1");
AddJob("2");
Console.WriteLine(GetNextJob());
AddJob("3");
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
AddJob("4");
AddJob("5");
Console.WriteLine(GetNextJob());
}
}
34. Queue program using C#
public class Queue_Program
{
private static List<string> jobs = new List<string>(16);
private static int nextJobPos = 0;
public static void AddJob(string jobName)
{
jobs.Add(jobName);
}
public static string GetNextJob()
{
if (nextJobPos > jobs.Count - 1)
return "NO JOBS IN BUFFER";
else
{
string jobName = jobs[nextJobPos];
nextJobPos++;
return jobName;
}
}
public static void Main()
{
AddJob("1");
AddJob("2");
Console.WriteLine(GetNextJob());
AddJob("3");
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
Console.WriteLine(GetNextJob());
AddJob("4");
AddJob("5");
Console.WriteLine(GetNextJob());
35. Construction of binary tree
Travelling
In order
Pre order
Post order
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class NodeList<T> :
System.Collections.ObjectModel.Collection<Node<T>>
{
public NodeList() : base() { }
public NodeList(int initialSize)
{
// Add the specified number of items
for (int i = 0; i < initialSize; i++)
base.Items.Add(default(Node<T>));
}
public Node<T> FindByValue(T value)
{
// search the list for the value
foreach (Node<T> node in Items)
if (node.Value.Equals(value))
return node;
// if we reached here, we didn't find a matching node
return null;
}
public class Node<T>
{
// Private member-variables
private T data;
private NodeList<T> neighbors = null;
public Node() { }
public Node(T data) : this(data, null) { }
public Node(T data, NodeList<T> neighbors)
{
this.data = data;
this.neighbors = neighbors;
}
public T Value
{
get
{
return data;
}
set
{
data = value;
}
}
protected NodeList<T> Neighbors
{
get
{
return neighbors;
}
set
{
neighbors = value;
}
}
}
public class BinaryTree<T>
{
private BinaryTreeNode<T> root;
public BinaryTree()
{
root = null;
}
public virtual void Clear()
{
root = null;
}
public BinaryTreeNode<T> Root
{
get
{
return root;
}
set
{
root = value;
}
}
}
public class BinaryTreeNode<T> : Node<T>
{
public BinaryTreeNode() : base() { }
public BinaryTreeNode(T data) : base(data, null) { }
public BinaryTreeNode(T data, BinaryTreeNode<T> left, BinaryTreeNode<T>
right)
{
base.Value = data;
NodeList<T> children = new NodeList<T>(2);
children[0] = left;
children[1] = right;
base.Neighbors = children;
}
public BinaryTreeNode<T> Left
{
get
{
if (base.Neighbors == null)
return null;
else
return (BinaryTreeNode<T>)base.Neighbors[0];
}
set
{
if (base.Neighbors == null)
base.Neighbors = new NodeList<T>(2);
base.Neighbors[0] = value;
}
}
public BinaryTreeNode<T> Right
{
get
{
if (base.Neighbors == null)
return null;
else
return (BinaryTreeNode<T>)base.Neighbors[1];
}
set
{
if (base.Neighbors == null)
base.Neighbors = new NodeList<T>(2);
base.Neighbors[1] = value;
}
}
}
public class Binary_Tree
{
public static void PreorderTraversal(BinaryTreeNode<int> current)
{
if (current != null)
{
// Output the value of the current node
Console.WriteLine(current.Value);
// Recursively print the left and right children
PreorderTraversal(current.Left);
PreorderTraversal(current.Right);
}
}
public static void InorderTraversal(BinaryTreeNode<int> current)
{
if (current != null)
{
// Visit the left child...
InorderTraversal(current.Left);
// Output the value of the current node
Console.WriteLine(current.Value);
// Visit the right child...
InorderTraversal(current.Right);
}
}
public static void PostorderTraversal(BinaryTreeNode<int>
{
if (current != null)
{
// Visit the left child...
PostorderTraversal(current.Left);
// Visit the right child...
PostorderTraversal(current.Right);
// Output the value of the current node
Console.WriteLine(current.Value);
}
}
public static void Main(string[] args)
{
BinaryTree<int> btree = new BinaryTree<int>();
btree.Root = new BinaryTreeNode<int>(1);
btree.Root.Left = new BinaryTreeNode<int>(2);
btree.Root.Right = new BinaryTreeNode<int>(3);
btree.Root.Left.Left = new BinaryTreeNode<int>(4);
btree.Root.Right.Right = new BinaryTreeNode<int>(5);
btree.Root.Left.Left.Right = new BinaryTreeNode<int>(6);
btree.Root.Right.Right.Right = new BinaryTreeNode<int>(7);
btree.Root.Right.Right.Right.Right = new BinaryTreeNode<int>(8);
Console.WriteLine("Pre Order");
PreorderTraversal(btree.Root);
Console.WriteLine("in Order");
InorderTraversal(btree.Root);
Console.WriteLine("post Order");
PostorderTraversal(btree.Root);
Console.ReadLine();
}