Your SlideShare is downloading. ×
C# labprograms
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

C# labprograms

1,729
views

Published on


0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,729
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
258
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. .Net Laboratory Subject Code: MCA655 CIE Marks : 50 Hours/Week : 04 No of Credits: 1.5 Total Hours : 42 1.Write a Program in C# to Check whether a number is Palindrome or not. using System; class Palindrome { public static void Main( ) { //Declaring the variables int num; int initial_num; int digit; int reverse_number = 0; //prompt the user for a number Console.WriteLine("*******************"); Console.WriteLine("Provide a number"); Console.WriteLine("*******************"); Console.WriteLine("rn"); //read in the users input initial_num = int.Parse(Console.ReadLine()); num = initial_num; do { //set digit to the users number mod 10 digit = initial_num % 10; //reverse the number by multiplying it by 10 then //adding digit to it reverse_number = reverse_number * 10 + digit; initial_num /= 10; } while (initial_num != 0); //print out the number reversed Console.WriteLine("************************"); Console.WriteLine("The reverse of the numer is: {0}", reverse_number); Console.WriteLine("************************"); Console.WriteLine("rn"); //now check to see if the number is a palidrome if (num == reverse_number) { //since the number entered = the number reversed it is a palidrome Console.WriteLine("*******************************"); Console.WriteLine("This number is a palindrome!"); Console.WriteLine("*******************************"); Console.WriteLine("rn"); } else
  • 2. { //number isnt a palidrome Console.WriteLine("*******************************"); Console.WriteLine("This number is not a palindrome"); Console.WriteLine("*******************************"); } } 2.Write a Program in C# to demonstrate Command line arguments Processing. using System; class CmdArgs{ public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments submitted"); Console.ReadLine(); return; } // processing a single argument Console.WriteLine("Squared Argument" + Environment.NewLine); // create variables to hold arguments Int32 orginalValue = 0; Int32 squaredValue = 0; try { orginalValue = int.Parse(args[0].ToString()); //first argument only squaredValue = orginalValue * orginalValue; Console.WriteLine(Environment.NewLine + Convert.ToString(orginalValue) + " Squared = " + Convert.ToString(squaredValue) + Environment.NewLine); Console.ReadLine(); return; } catch { // display indication of invalid input from command line Console.WriteLine(Environment.NewLine + "Invalid Input" + Environment.NewLine); Console.ReadLine(); return; } } }
  • 3. using System; class cmd2{ static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments submitted"); Console.ReadLine(); return; } Console.WriteLine("Add All" + Environment.NewLine); // create variables to hold arguments int RunningTotal = 0; // populate the variables from the arguments for (int i = 0; i < args.Length; i++) { try { RunningTotal = RunningTotal + Convert.ToInt32(args[i].ToString()); } catch { // Display error if input is missing or invalid Console.WriteLine(Environment.NewLine + "Invalid Input" + Environment.NewLine); Console.ReadLine(); return; } } Console.WriteLine(Environment.NewLine + "All numbers added = " + RunningTotal.ToString() + Environment.NewLine); Console.ReadLine(); return; } }
  • 4. 3.Write a Program in C# to find the roots of Quadratic Equation. using System; class Quad { public static void Main() { int A, B, C; double disc, deno, x1, x2; Console.WriteLine("ENTER THE VALUES OF A,B,C..."); A=int.Parse(Console.ReadLine()); B=int.Parse(Console.ReadLine()); C=int.Parse(Console.ReadLine()); disc = (B * B) - (4 * A * C); deno = 2 * A; if(disc > 0) { Console.WriteLine("THE ROOTS ARE REAL ROOTS"); x1 = (-B/deno) + (Math.Sqrt(disc) / deno); x2 = (-B/deno) - (Math.Sqrt(disc) / deno); Console.WriteLine("THE ROOTS ARE...: {0} and {1}", x1, x2); } else if(disc == 0) { Console.WriteLine("THE ROOTS ARE REPEATED ROOTS"); x1 = -B/deno; Console.WriteLine("THE ROOT IS...: {0}", x1); } else { Console.WriteLine("THE ROOTS ARE IMAGINARY ROOTSn"); x1 = -B/deno; x2 = ((Math.Sqrt((4*A*C)-(B*B))) / deno); Console.WriteLine("THE ROOT ONE...: {0}+i{1}", x1, x2); Console.WriteLine("THE ROOTS ARE...: {0}-i{1}", x1, x2); } } }
  • 5. 4.Write a Program in C# to demonstrate boxing and unBoxing. class TestUnboxing { static void Main() { int i = 123; object o = i; // implicit boxing try { //int j = (short)o; // attempt to unbox int j = (int)o; // attempt to unbox System.Console.WriteLine("Unboxing OK."); } catch (System.InvalidCastException e) { System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message); } } }
  • 6. 5.Write a Program in C# to implement Stack operations. namespace Stack { using System; public class Stack { private Node first = null; private int count = 0; /******************************************************************************* *********************************** Property Procedures do not accept any parameters. Note the diff in the function definition (no parenthesis) ******************************************************************************** ***********************************/ public bool Empty { /******************************************* Property Get Procedure ********************************************/ get { return (first == null); } } public int Count { /******************************************* Property Get Procedure ********************************************/ get { return count; } } public object Pop() { if (first == null) { throw new InvalidOperationException ("Cant pop from an empty stack"); } else { object temp = first.Value; first = first.Next; count--; return temp; } } public void Push(object o) { first = new Node(o, first);
  • 7. count++; } class Node { public Node Next; public object Value; public Node(object value) : this(value, null) {} public Node(object value, Node next) { Next = next; Value = value; } } } class StackTest { static void Main() { Stack s = new Stack(); if (s.Empty) Console.WriteLine("Stack is Empty"); else Console.WriteLine("Stack is not Empty"); for (int i = 0; i < 5; i++) s.Push(i); Console.WriteLine("Items in Stack {0}", s.Count); for (int i = 0; i < 5; i++) Console.WriteLine("Popped Item is {0} and the count is {1}", s.Pop(), s.Count); s = null; } } }
  • 8. using System; using System.Collections; using System.Windows.Forms; using System.Drawing; class StackDemo : Form { static Stack simpleStack; Button btnPush,btnPeek,btnPop; TextBox txtItem; Label lblItem,lblStack; ListBox lstStackUI; public StackDemo() { simpleStack = new Stack(32); lblItem = new Label(); lblItem.Text = "Item To Add"; lblItem.Location = new Point(16,16); lblItem.AutoSize = true; txtItem = new TextBox(); txtItem.Location = new Point(lblItem.Right + 8 ,lblItem.Top); txtItem.Size = new Size(256,27); btnPush = new Button(); btnPush.Size = btnPush.Size; btnPush.Location = new Point(txtItem.Right + 8,lblItem.Top); btnPush.Text = "Push"; btnPush.Click += new EventHandler(btnPush_Click); btnPeek = new Button(); btnPeek.Size = btnPush.Size; btnPeek.Location = new Point(btnPush.Right + 8,lblItem.Top); btnPeek.Text = "Peek"; btnPeek.Click += new EventHandler(btnPeek_Click); btnPop = new Button(); btnPop.Size = btnPush.Size; btnPop.Location = new Point(btnPeek.Right + 8,lblItem.Top); btnPop.Text = "Pop"; btnPop.Click += new EventHandler(btnPop_Click); lblStack = new Label(); lblStack.Location = new Point(lblItem.Left,lblItem.Bottom + 32); lblStack.Text = "Visual Stack"; lstStackUI = new ListBox(); lstStackUI.Location = new Point(lblItem.Left,lblStack.Bottom + 16); lstStackUI.Size = new Size(512,256); this.Text = "Stack Demo"; this.Controls.AddRange( new Control[] { lblItem,txtItem, btnPush,btnPeek,btnPop, lblStack,lstStackUI }); }
  • 9. //Push element to the stack void btnPush_Click(object sender,EventArgs e) { if(txtItem.Text.Trim() != String.Empty) { simpleStack.Push(txtItem.Text.Trim()); lstStackUI.Items.Insert(0,"Pushed : " + txtItem.Text.Trim() + " At " + DateTime.Now.ToString()); } else { MessageBox.Show("Empty Value Cannot be Added","StackDemo", MessageBoxButtons.OK,MessageBoxIcon.Information); } } //How to get the top element of the Stack? void btnPeek_Click(object sender,EventArgs e) { try { MessageBox.Show("Peek Element: " + simpleStack.Peek().ToString()); } catch(Exception ex) { MessageBox.Show("Error: " + ex.Message,"StackDemo", MessageBoxButtons.OK,MessageBoxIcon.Error); } } //Method to show how to pop element from the Stack. void btnPop_Click(object sender,EventArgs e) { try { MessageBox.Show("Popped Element: " + simpleStack.Pop().ToString()); lstStackUI.Items.RemoveAt(0); } catch(Exception ex) { MessageBox.Show("Error: " + ex.Message,"StackDemo", MessageBoxButtons.OK,MessageBoxIcon.Error); } } static void Main() { Application.Run(new StackDemo()); } }
  • 10. 6.Write a program to demonstrate Operator overloading. // Source Code starts using System; class Square { private double Side; //public Constructor if int is passed convert to double and assign to Side public Square(int s) { Console.WriteLine(".ctor with int argument"); Side=(double)s; } //OverLoaded constructor with double argument public Square(double s) { Console.WriteLine(".ctor with double argument"); Side=s; } //override ToString() method of object class. public override string ToString() { Console.WriteLine("Override object class's string"); return this.Side.ToString(); } //Overloading + operator to add 2 square objects and return new square object public static Square operator + (Square x,Square y) { Console.WriteLine("Overloading + with Square,Square"); return new Square(x.Side+y.Side); } //Overloading + operator to add square objects with double side and return new square object public static Square operator + (Square x,double y) { Console.WriteLine("Overloading + with Square,double"); return new Square(x.Side+y); } //Overloading + operator to add square objects with int side and return new square object //This is not necessary since C# automatically calls +(Square,double) public static Square operator + (Square x,int y) { Console.WriteLine("Overloading + with Square,int"); return x +(double)y; } public static implicit operator Square(double s) { Console.WriteLine("Overloading = for Square s5=1.5 assignment"); return new Square(s); } public static implicit operator Square(int s) { Console.WriteLine("Overloading = for Square s5=10 assignment");
  • 11. return new Square((double)s); } //OverLoading == operator public static bool operator ==(Square x,Square y) { Console.WriteLine("Overloading == with Square,Square"); return x.Side==y.Side; } //OverLoading != operator public static bool operator !=(Square x,Square y) { Console.WriteLine("Overloading != with Square,Square"); return !(x==y); //This will call to operator == simple way to implement != } //Always override GetHashCode(),Equals when overloading == public override bool Equals(object o) { return this==(Square)o; } public override int GetHashCode() { return (int)Side; } //OverLoading > operator public static bool operator >(Square x,Square y) { Console.WriteLine("Overloading > with Square,Square"); return x.Side>y.Side; } //OverLoading < operator public static bool operator <(Square x,Square y) { Console.WriteLine("Overloading < with Square,Square"); return x.Side<y.Side; } //OverLoading <= operator public static bool operator <=(Square x,Square y) { Console.WriteLine("Overloading <= with Square,Square"); return (x<y) || (x==y); //Calls to operator == and < } //OverLoading >= operator public static bool operator >=(Square x,Square y) { Console.WriteLine("Overloading >= with Square,Square"); return (x>y) || (x==y); //Calls to operator == and > } //Readonly Property public double Area { get { return 2*Side; } } public static void Main()
  • 12. { Square s1=new Square(10); Square s2=new Square(20); Square s3=s1+s2; // This will call operator + (Square,Square) Console.WriteLine(s3); Console.WriteLine(s3+15); // This will call operator + (Square,int) and then ToString() Console.WriteLine(s3+1.5);// This will call operator + (Square,double) and then ToString() s3=10; // This will call operator Square(int) Console.WriteLine(s3); Square s4=10; Console.WriteLine(s1==s4); //Calls == operator Console.WriteLine(s1!=s4); //Calls != operator Console.WriteLine(s1>s2); //Calls > operator Console.WriteLine(s1<=s4); //Calls <= operator } }
  • 13. 7.Write a Program in C# to find the second largest element in a single dimensional array. using System; class Biggest { int[] a={1,2,3,4}; public void ReadElement() { Console.WriteLine("n Enter the elements:"); for(int i=0;i<a.Length;i++) { a[i]=int.Parse(Console.ReadLine()); } } public void PrintElement() { Console.WriteLine("n The elements are:"); for(int i=0;i<a.Length;i++) { Console.WriteLine(a[i]); } } public void BigElement() { int big, sec; big=sec=a[0]; for(int i=1;i<a.Length;i++) { if(big < a[i]) { sec = big; big=a[i]; } } Console.WriteLine("first biggest {0} and second biggest {1}",big,sec); } } class Big { public static void Main() { Biggest MM=new Biggest(); MM.ReadElement(); MM.PrintElement(); MM.BigElement(); } }
  • 14. 8.Write a Program in C# to multiply to matrices using Rectangular arrays. using System; class MatrixMultiplication { int[,] a; int[,] b; int[,] c; public void ReadMatrix() { Console.WriteLine("n Size of Matrix 1:"); Console.Write("n Enter the number of rows in Matrix 1 :"); int m=int.Parse(Console.ReadLine()); Console.Write("n Enter the number of columns in Matrix 1 :"); int n=int.Parse(Console.ReadLine()); a=new int[m,n]; Console.WriteLine("n Enter the elements of Matrix 1:"); for(int i=0;i<a.GetLength(0);i++) { for(int j=0;j<a.GetLength(1);j++) { a[i,j]=int.Parse(Console.ReadLine()); } } Console.WriteLine("n Size of Matrix 2 :"); Console.Write("n Enter the number of rows in Matrix 2 :"); m=int.Parse(Console.ReadLine()); Console.Write("n Enter the number of columns in Matrix 2 :"); n=int.Parse(Console.ReadLine()); b=new int[m,n]; Console.WriteLine("n Enter the elements of Matrix 2:"); for(int i=0;i<b.GetLength(0);i++) { for(int j=0;j<b.GetLength(1);j++) { b[i,j]=int.Parse(Console.ReadLine()); } } } public void PrintMatrix() { Console.WriteLine("n Matrix 1:"); for(int i=0;i<a.GetLength(0);i++) { for(int j=0;j<a.GetLength(1);j++) { Console.Write("t"+a[i,j]); } Console.WriteLine(); } Console.WriteLine("n Matrix 2:"); for(int i=0;i<b.GetLength(0);i++) {
  • 15. for(int j=0;j<b.GetLength(1);j++) { Console.Write("t"+b[i,j]); } Console.WriteLine(); } Console.WriteLine("n Resultant Matrix after multiplying Matrix 1 & Matrix 2:"); for(int i=0;i<c.GetLength(0);i++) { for(int j=0;j<c.GetLength(1);j++) { Console.Write("t"+c[i,j]); } Console.WriteLine(); } } public void MultiplyMatrix() { if(a.GetLength(1)==b.GetLength(0)) { c=new int[a.GetLength(0),b.GetLength(1)]; for(int i=0;i<c.GetLength(0);i++) { for(int j=0;j<c.GetLength(1);j++) { c[i,j]=0; for(int k=0;k<a.GetLength(1);k++) // OR k<b.GetLength(0) c[i,j]=c[i,j]+a[i,k]*b[k,j]; } } } else { Console.WriteLine("n Number of columns in Matrix1 is not equal to Number of rows in Matrix2."); Console.WriteLine("n Therefore Multiplication of Matrix1 with Matrix2 is not possible"); Environment.Exit(-1); } } } class Matrices { public static void Main() { MatrixMultiplication MM=new MatrixMultiplication(); MM.ReadMatrix(); MM.MultiplyMatrix(); MM.PrintMatrix(); } }
  • 16. 9. Find the sum of all the elements present in a jagged array of 3 inner arrays. using System; class JagArray { public static void Main() { int [][] myJagArray = new int[3][]; for(int i=0; i<myJagArray.Length;i++) { myJagArray[i] = new int[i+3]; } for(int i=0; i<3;i++) { Console.WriteLine("Enter {1} Elements of row {0}",i,myJagArray[i].Length); for(int j=0; j<myJagArray[i].Length;j++) { myJagArray[i][j]=int.Parse(Console.ReadLine()); } Console.WriteLine(); } int sum=0; for(int i=0; i<3;i++) { for(int j=0; j<myJagArray[i].Length;j++) { sum += myJagArray[i][j]; } } Console.WriteLine("The sum of Jagged Array is {0}", sum); } } 10.Write a program to reverse a given string using C#. using System; class RevStr { public static string Reverse(string str) { int len = str.Length; char[] arr = new char[len]; for (int i = 0; i < len; i++) { arr[i] = str[len - 1 - i]; } return new string(arr); }
  • 17. public static void Main() { string str; string revstr; str=Console.ReadLine(); revstr=Reverse(str); Console.WriteLine(revstr); } } 11. Using Try, Catch and Finally blocks write a program in C# to demonstrate error handling. using System; class TryCatch{ public static void Main() { int a, b = 0 ; Console.WriteLine( "My program starts" ) ; try { a = 10 / b; } catch ( InvalidOperationException e ) { Console.WriteLine ( e ) ; } catch ( DivideByZeroException e) { Console.WriteLine ( e ) ; } finally { Console.WriteLine ( "finally" ) ; } Console.WriteLine ( "Remaining program" ) ; } } using System; class TryCatch { public static void Main() { int a, b = 0 ; Console.WriteLine( "My program starts" ) try { a = 10 / b; } finally
  • 18. { Console.WriteLine ( "finally" ) ; } Console.WriteLine ( "Remaining program" ) ; } } 12. Design a simple calculator using Switch Statement in C#. using System; using System.Windows.Forms; using System.Drawing; public class win:Form { Button[] b = new Button[10]; Button bDot,bPlus,bSub,bMul,bDiv,bEqu,bClr; Panel panCalc; TextBox txtCalc; Double dblAcc; Double dblSec; bool blnClear,blnFrstOpen; String strOper; public win() { try { this.Text="Calculator"; panCalc=new Panel(); txtCalc = new TextBox(); txtCalc.Location = new Point(10,10); txtCalc.Size=new Size(150,10); txtCalc.ReadOnly=true; txtCalc.RightToLeft=RightToLeft.Yes; panCalc.Size=new Size(200,200); panCalc.BackColor=Color.Aqua; panCalc.Controls.Add(txtCalc); addButtons(panCalc); this.Size=new Size(200,225); this.Controls.Add(panCalc); dblAcc=0; dblSec=0; blnFrstOpen=true; blnClear=false; strOper=new String('=',1); } catch (Exception e) { Console.WriteLine("error ...... " + e.StackTrace); } } private void addButtons(Panel p) {
  • 19. for (int i=0;i<=9;i++) { b[i]=new Button(); b[i].Text=Convert.ToString(i); b[i].Size=new Size(25,25); b[i].BackColor=Color.White; b[i].Click+=new EventHandler(btn_clk); p.Controls.Add(b[i]); } b[0].Location=new Point(10,160); b[1].Location=new Point(10,120); b[4].Location=new Point(10,80); b[7].Location=new Point(10,40); b[2].Location=new Point(50,120); b[5].Location=new Point(50,80); b[8].Location=new Point(50,40); b[3].Location=new Point(90,120); b[6].Location=new Point(90,80); b[9].Location=new Point(90,40); bDot=new Button(); bDot.Size=new Size(25,25); bDot.Location=new Point(50,160); bDot.BackColor=Color.White; bDot.Text="."; bDot.Click+=new EventHandler(btn_clk); bPlus=new Button(); bPlus.Size=new Size(25,25); bPlus.Location=new Point(130,160); bPlus.BackColor=Color.White; bPlus.Text="+"; bPlus.Click+=new EventHandler(btn_Oper); bSub=new Button(); bSub.Size=new Size(25,25); bSub.Location=new Point(130,120); bSub.BackColor=Color.White; bSub.Text="-"; bSub.Click+=new EventHandler(btn_Oper); bMul=new Button(); bMul.Size=new Size(25,25); bMul.Location=new Point(130,80); bMul.BackColor=Color.White; bMul.Text="*"; bMul.Click+=new EventHandler(btn_Oper); bDiv=new Button(); bDiv.Size=new Size(25,25); bDiv.Location=new Point(130,40); bDiv.BackColor=Color.White; bDiv.Text="/"; bDiv.Click+=new EventHandler(btn_Oper); bEqu=new Button();
  • 20. bEqu.Size=new Size(25,25); bEqu.Location=new Point(90,160); bEqu.BackColor=Color.White; bEqu.Text="="; bEqu.Click+=new EventHandler(btn_equ); bClr=new Button(); bClr.Size=new Size(20,45); bClr.Location=new Point(170,40); bClr.BackColor=Color.Orange; bClr.Text="AC"; bClr.Click+=new EventHandler(btn_clr); p.Controls.Add(bDot); p.Controls.Add(bPlus); p.Controls.Add(bSub); p.Controls.Add(bMul); p.Controls.Add(bDiv); p.Controls.Add(bEqu); p.Controls.Add(bClr); } private void btn_clk(object obj,EventArgs ea) { if(blnClear) txtCalc.Text=""; Button b3=(Button)obj; txtCalc.Text+=b3.Text; if (txtCalc.Text==".") txtCalc.Text="0."; dblSec=Convert.ToDouble(txtCalc.Text); blnClear=false; } private static void Main() { Application.Run(new win()); } private void btn_Oper(object obj,EventArgs ea) { Button tmp=(Button)obj; strOper=tmp.Text; if (blnFrstOpen) dblAcc=dblSec; else calc(); blnFrstOpen=false; blnClear=true; } private void btn_clr(object obj,EventArgs ea) { clear(); }
  • 21. private void btn_equ(object obj,EventArgs ea) { calc(); } private void calc() { switch(strOper) { case "+": dblAcc+=dblSec; break; case "-": dblAcc-=dblSec; break; case "*": dblAcc*=dblSec; break; case "/": dblAcc/=dblSec; break; } strOper="="; blnFrstOpen=true; txtCalc.Text=Convert.ToString(dblAcc); dblSec=dblAcc; } private void clear() { dblAcc=0; dblSec=0; blnFrstOpen=true; txtCalc.Text=""; txtCalc.Focus(); } } 13. Demonstrate Use of Virtual and override key words in C# with a simple program using System; public class Employee { // protected data for kids. protected string fullName; protected int empID; protected float currPay; protected string empSSN; #region Constructors // Default ctor. public Employee(){} // Custom ctor
  • 22. public Employee(string FullName, int empID, float currPay) { // Assign internal state data. // Note use of 'this' keyword // to avoid name clashes. this.fullName = FullName; this.empID = empID; this.currPay = currPay; } // If the user calls this ctor, forward to the 4-arg version // using arbitrary values... public Employee(string fullName) : this(fullName, 3333, 0.0F){} #endregion #region Methods // Bump the pay for this emp. public virtual void GiveBonus(float amount) {currPay += amount;} // Show state (could use ToString() as well) public virtual void DisplayStats() { Console.WriteLine("Name: {0}", fullName); Console.WriteLine("Pay: {0}", currPay); Console.WriteLine("ID: {0}", empID); } // Accessor & mutator for the FirstName. public string GetFullName() { return fullName; } public void SetFullName(string n) { // Remove any illegal characters (!,@,#,$,%), // check maximum length or case before making assignment. fullName = n; } #endregion #region properties // Property for the empID. public int EmpID { get {return empID;} set { #if DEBUG Console.WriteLine("value is an instance of: {0} ", value.GetType()); Console.WriteLine("value as string: {0} ", value.ToString()); #endif empID = value; } }
  • 23. // Property for the currPay. public float Pay { get {return currPay;} set {currPay = value;} } // Another property for ssn. public string SSN { get { return empSSN; } } #endregion } public class Manager : Employee { private ulong numberOfOptions; #region Constructors public Manager(){} public Manager(string FullName, int empID, float currPay, ulong numbOfOpts) : base(FullName, empID, currPay) { // This point of data belongs with us! numberOfOptions = numbOfOpts; } #endregion #region Methods and properties public override void GiveBonus(float amount) { // Increase salary. base.GiveBonus(amount); // And give some new stock options... Random r = new Random(); numberOfOptions += (ulong)r.Next(500); } public override void DisplayStats() { base.DisplayStats(); Console.WriteLine("Number of stock options: {0}", numberOfOptions); } public ulong NumbOpts { get {return numberOfOptions;}
  • 24. set { numberOfOptions = value;} } #endregion } public class SalesPerson : Employee { protected int numberOfSales; #region Constructors public SalesPerson(){} public SalesPerson(string FullName, int empID, float currPay, int numbOfSales) : base(FullName, empID, currPay) { numberOfSales = numbOfSales; } #endregion #region Properties and methods public int NumbSales { get {return numberOfSales;} set { numberOfSales = value;} } public override void GiveBonus(float amount) { int salesBonus = 0; if(numberOfSales >= 0 && numberOfSales <= 100) salesBonus = 10; else if(numberOfSales >= 101 && numberOfSales <= 200) salesBonus = 15; else salesBonus = 20; // Anything greater than 200. base.GiveBonus(amount * salesBonus); } public override void DisplayStats() { base.DisplayStats(); Console.WriteLine("Number of sales: {0}", numberOfSales); } #endregion } public class Virtual_override { public static void Main() {
  • 25. Manager mgr = new Manager("xyz",55,1000,200 ); mgr.GiveBonus(100); mgr.DisplayStats(); SalesPerson sp = new SalesPerson("abc",44,10000,200); sp.GiveBonus(100); sp.DisplayStats(); } } 14. Implement linked lists in C# using the existing collections name space. using System; using System.Collections.Generic; namespace Interview { class Program { static int ListLength = 10; static void Main(string[] args) { // Create a non-circular list ListItem.Head.Data = 0; ListItem i = ListItem.Head; for (int d = 1 ; d < ListLength; d++) { ListItem n = new ListItem(d); i.InsertAfter(n); i = n; } ListItem.PrintToConsole(); Console.WriteLine(); int randpos = new Random().Next(ListLength); Console.WriteLine("Target: {0}", randpos); ListItem target = ListItem.FindData(randpos); target.InsertAfter(new ListItem("InsertAfter")); ListItem.PrintToConsole(); Console.WriteLine(); target.InsertBeforeUsingHead(new ListItem("InsertBeforeUsingHead")); ListItem.PrintToConsole(); Console.WriteLine(); target.InsertBeforeWithoutHead(new ListItem("InsertBeforeWithoutHead")); ListItem.PrintToConsole(); Console.WriteLine(); target = ListItem.FindData(randpos); target.DeleteAfter(); ListItem.PrintToConsole(); Console.WriteLine(); target = target.FindPrevious(); target.DeleteCurrentUsingHead(); ListItem.PrintToConsole(); Console.WriteLine(); target = ListItem.FindData(randpos).FindPrevious(); target.DeleteCurrentWithoutHead();
  • 26. ListItem.PrintToConsole(); Console.WriteLine(); target = ListItem.MiddleItem; Console.WriteLine("Middle Item: {0}", target.Data); ListItem.Reverse(); ListItem.PrintToConsole(); Console.WriteLine(); Console.WriteLine("Is Circular: {0}", target.IsCircular.ToString()); target = ListItem.FindData(0); target.Next = ListItem.Head; Console.WriteLine("Is Circular: {0}", target.IsCircular.ToString()); #if(DEBUG) // Pause in the console if this is a debug run Console.ReadLine(); #endif } } class ListItem { // I use a static head because it simplifies the example. // Not practical if you want more than one list. static public ListItem Head {get; set; } static ListItem() { Head = new ListItem(); } public object Data { get; set; } public ListItem() { Next = null; Data = new object(); } public ListItem(object data) { Next = null; Data = data; } public ListItem Next { get; set; } // Simple list insertion public ListItem InsertAfter(ListItem i) { i.Next = this.Next; this.Next = i; return i; } // This is the common way to traverse a linked list for an insert before public void InsertBeforeUsingHead(ListItem i) { ListItem p = FindPrevious(); if (p == null) { // When current is the lead node its possible that its an orphan node. You can often leave this out since its a side // effect of the example code infrastructure. if (this != Head) throw new InvalidOperationException("Cannot insert before an orphan item"); i.Next = Head; Head = i; }
  • 27. else { p.InsertAfter(i); } } // This one appears to be an insert after, but since the data values are swapped // it is equivalent to an insert before. Use this to surprise interviewers with your // clever out of box thinking. public void InsertBeforeWithoutHead(ListItem i) { object o = this.Data; this.Data = i.Data; i.Data = o; this.InsertAfter(i); } // Simple O(n) list traversal public ListItem FindPrevious() { ListItem i; if (this == Head) return null; // There is need for a null test here since the code constructor logic permits // the creation of nodes that are not linked for (i = Head; (i != null) && (i.Next != this); i = i.Next ) ; return i; } // Simple delete operation public void DeleteAfter() { if (this.Next == null) return; ListItem i = this.Next; if (i == this) // Last node in circular list { Head = null; } this.Next = i.Next; } // Simple delete operation public void DeleteCurrentUsingHead() { ListItem p = FindPrevious(); if (p == null) if (p == Head) { Head = this.Next; } else { throw new InvalidOperationException("Delete the last node of an orphan by nulling its reference."); } p.DeleteAfter();
  • 28. } // A faster way to delete a node public void DeleteCurrentWithoutHead() { if (this.Next == null) { // If an interviewer asks you to delete a node without using the head node // then you would just return here. But, you have to do the list traverse // if this is the last node in the list DeleteCurrentUsingHead(); } else { // Speedy trick if there is a node following the current one this.Data = Next.Data; DeleteAfter(); } } // The trick is to create two pointers, one that increments once, and another that increments twice. // If the faster pointer overtakes the slower one, then you have a circular list public bool IsCircular { get { ListItem j = this; for (ListItem i = this; (i != null) && (i.Next != null); i = i.Next) { if (j.Next == null || j.Next.Next == null) return false; if (j.Next == i || j.Next.Next == i) return true; j = j.Next.Next; } return false; // the loop falls through when the item is the last in list } } // Same trick as the circular test. In fact, if this returns null // than you either have a circular list or a null head pointer. If you have an even number of items, // the middle is defined as the item to the left of middle. static public ListItem MiddleItem { get { ListItem j = Head; for (ListItem i = Head; (i != null) && (i.Next != null); i = i.Next) { if (j.Next == null || j.Next.Next == null) return i; if (j.Next == i || j.Next.Next == i) return null; // Circular list test j = j.Next.Next; } return Head; // the loop falls through when the item is only item or head is null } } // This method reverses the linked list. static public void Reverse()
  • 29. { ListItem r = null; ListItem i = Head; ListItem h = Head; while (i != null) { h = i.Next; i.Next = r; r = i; i = h; } Head = r; } static public void PrintToConsole() { for (ListItem i = Head; (i != null); i = i.Next) { if (i.Data != null) Console.Write(i.Data.ToString()); else Console.Write("Node"); if (i.Next != null) Console.Write(", "); if (i.Next == Head) break; // Circular list } } // Handy iterator. Try this with Linq! static public IEnumerable<ListItem> Items { get { if (Head == null) yield return Head; else for (ListItem i = Head; i != null; i = i.Next) yield return i; } } static public ListItem FindData(object data) { foreach (ListItem item in ListItem.Items) { if (item.Data.Equals(data)) { return item; } } return null; } } }
  • 30. 15. Write a program to demonstrate abstract class and abstract methods in C#. using System; // Abstract base class. public abstract class Shape { protected string petName; // Constructors. public Shape(){petName = "NoName";} public Shape(string s) { this.petName = s; } // All child objects must define for themselves what // it means to be drawn. public abstract void Draw(); public string PetName { get {return this.petName;} set {this.petName = value;} } } #region rerived types. public class Circle : Shape { public Circle(){} // Call base class constructor. public Circle(string name): base(name){} public override void Draw() { Console.WriteLine("Drawing " + PetName + " the Circle"); } } public class Oval : Circle { public Oval(){base.PetName = "Joe";} // Hide base class impl if they create an Oval. new public void Draw() { Console.WriteLine("Drawing an Oval using a very fancy algorithm"); } } public class Hexagon : Shape { public Hexagon(){} public Hexagon(string name): base(name){}
  • 31. public override void Draw() { Console.WriteLine("Drawing " + PetName + " the Hexagon"); } } #endregion public class ShapesApp { public static int Main(string[] args) { // The C# base class pointer trick. Console.WriteLine("***** Using an array of base class references *****"); Shape[] s = {new Hexagon(), new Circle(), new Hexagon("Mick"), new Circle("Beth"), new Hexagon("Linda")}; for(int i = 0; i < s.Length; i++) { s[i].Draw(); } // Oval hides the base class impl of Draw() // and calls its own version. Console.WriteLine("n***** Calling Oval.Draw() *****"); Oval o = new Oval(); o.Draw(); return 0; } } 16. Write a program in C# to build a class which implements an interface which is already existing. using System; using System.Collections; public class SamplesArray { public class myReverserClass : IComparer { // Calls CaseInsensitiveComparer.Compare with the parameters reversed. int IComparer.Compare( Object x, Object y ) { return( (new CaseInsensitiveComparer()).Compare( y, x ) ); } } public static void Main() { // Creates and initializes a new Array and a new custom comparer. String[] myArr = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", "the", "lazy", "dog" }; IComparer myComparer = new myReverserClass(); // Displays the values of the Array. Console.WriteLine( "The Array initially contains the following values:" );
  • 32. PrintIndexAndValues( myArr ); // Sorts a section of the Array using the default comparer. Array.Sort( myArr, 1, 3 ); Console.WriteLine( "After sorting a section of the Array using the default comparer:" ); PrintIndexAndValues( myArr ); // Sorts a section of the Array using the reverse case-insensitive comparer. Array.Sort( myArr, 1, 3, myComparer ); Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" ); PrintIndexAndValues( myArr ); // Sorts the entire Array using the default comparer. Array.Sort( myArr ); Console.WriteLine( "After sorting the entire Array using the default comparer:" ); PrintIndexAndValues( myArr ); // Sorts the entire Array using the reverse case-insensitive comparer. Array.Sort( myArr, myComparer ); Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" ); PrintIndexAndValues( myArr ); } public static void PrintIndexAndValues( String[] myArr ) { for ( int i = 0; i < myArr.Length; i++ ) { Console.WriteLine( " [{0}] : {1}", i, myArr[i] ); } Console.WriteLine(); } } 17.Write a program to illustrate the use of different properties in C#. The following example shows how to define abstract properties. An abstract property declaration does not provide an implementation of the property accessors. The example demonstrates how to override these properties in subclasses. This sample consists of three files. In the Properties Sample, these files are compiled into a single compilation but in this tutorial, each file is compiled individually and its resulting assembly referenced by the next compilation: abstractshape.cs: The Shape class that contains an abstract Area property. shapes.cs: The subclasses of the Shape class. shapetest.cs: A test program to display the areas of some Shape-derived objects. To compile the example, use the command line: csc abstractshape.cs shapes.cs shapetest.cs This will create the executable file shapetest.exe. // abstractshape.cs // compile with: /target:library // csc /target:library abstractshape.cs using System; public abstract class Shape
  • 33. { private string myId; public Shape(string s) { Id = s; // calling the set accessor of the Id property } public string Id { get { return myId; } set { myId = value; } } // Area is a read-only property - only a get accessor is needed: public abstract double Area { get; } public override string ToString() { return Id + " Area = " + string.Format("{0:F2}",Area); } } // shapes.cs // compile with: /target:library /reference:abstractshape.dll public class Square : Shape { private int mySide; public Square(int side, string id) : base(id) { mySide = side; } public override double Area { get { // Given the side, return the area of a square: return mySide * mySide; } } } public class Circle : Shape {
  • 34. private int myRadius; public Circle(int radius, string id) : base(id) { myRadius = radius; } public override double Area { get { // Given the radius, return the area of a circle: return myRadius * myRadius * System.Math.PI; } } } public class Rectangle : Shape { private int myWidth; private int myHeight; public Rectangle(int width, int height, string id) : base(id) { myWidth = width; myHeight = height; } public override double Area { get { // Given the width and height, return the area of a rectangle: return myWidth * myHeight; } } } // shapetest.cs // compile with: /reference:abstractshape.dll;shapes.dll public class TestClass { public static void Main() { Shape[] shapes = { new Square(5, "Square #1"), new Circle(3, "Circle #1"), new Rectangle( 4, 5, "Rectangle #1") }; System.Console.WriteLine("Shapes Collection"); foreach(Shape s in shapes) { System.Console.WriteLine(s); }
  • 35. } } 18. Demonstrate arrays of interface types with a C# program.