c# QBANK SOL (1)

100
Question Bank Solution for C# 1 | Page DECISION MAKING, LOOPING AND BRANCHING: Q.1 Write a program to encode or decode a message typed by user. To encode increment each character by 1(A becomes B, B becomes C and so on). To decode decrement each character by 1(C becomes B, B becomes A and so on). (Hint: use char for type conversion) A. using System; Class Cipher { Public static int Main (string [] args) { // see if arguments are present If (args.Length < 2) { Console.WriteLine ("encode/decode word"); Return 1; // return failure code } // if args present, first arg must be encode or decode If (args [0]! = "encode" & args [0]! = "decode") { Console.WriteLine ("First arg must be encode or decode."); Return 1; // return failure code } // encode or decode message For (int n=1; n < args.Length; n++) { For (int i=0; i < args[n].Length; i++) { If (args [0] == "encode") Console.Write ((char) (args[n][i] + 1) ); Else Console.Write ((char) (args[n][i] - 1) ); } Console.Write (" "); } Console.WriteLine (); Return 0; } } Q.2 Write a program to display the below output: 10 20 30 40 60 70 80 90 A. using System;

Transcript of c# QBANK SOL (1)

Page 1: c# QBANK SOL (1)

Question Bank Solution for C#

1 | P a g e

DECISION MAKING, LOOPING AND BRANCHING:

Q.1 Write a program to encode or decode a message typed by user. To encode increment each

character by 1(A becomes B, B becomes C and so on). To decode decrement each character by

1(C becomes B, B becomes A and so on). (Hint: use char for type conversion)

A. using System;

Class Cipher

{

Public static int Main (string [] args)

{

// see if arguments are present

If (args.Length < 2)

{

Console.WriteLine ("encode/decode word");

Return 1; // return failure code

}

// if args present, first arg must be encode or decode

If (args [0]! = "encode" & args [0]! = "decode")

{

Console.WriteLine ("First arg must be encode or decode.");

Return 1; // return failure code

}

// encode or decode message

For (int n=1; n < args.Length; n++)

{

For (int i=0; i < args[n].Length; i++)

{

If (args [0] == "encode")

Console.Write ((char) (args[n][i] + 1) );

Else

Console.Write ((char) (args[n][i] - 1) );

}

Console.Write (" ");

}

Console.WriteLine ();

Return 0;

}

}

Q.2 Write a program to display the below output:

10 20 30 40

60 70 80 90

A. using System;

Page 2: c# QBANK SOL (1)

Question Bank Solution for C#

2 | P a g e

Class ContinueBreak

{

public static void Main()

{

int n=10;

while (n<200)

{

if (n<50)

{

Console.Write (― ‖+n);

n=n+10;

continue;

}

if (n == 50)

{

Console.Write ();

n=n+10;

continue;

}

if (n > 90) break;

Console.Write (― ‖+n);

n=n+10;

}

Console.Writeline ();

}

}

Page 3: c# QBANK SOL (1)

Question Bank Solution for C#

3 | P a g e

Q.3 Using Switch-case, allow the users to select the size of cola can. Based on the user selection the

program prints the amount the user must pay for the particular type of can selected.

A. using System;

Class Cola

{

Public static void Main ()

{

Console.WriteLine (―Select your Cola Can‖);

Console.WriteLine (―S=Small M=Medium L=Large‖);

Console.Write (―Plz. Select an option‖);

String s= Console.Readline ();

int cost=0;

Switch (s)

{

Case ―S‖:

cost =cost+10;

break;

Case ―M‖:

cost =cost+15;

break;

Case ―L‖:

cost =cost+30;

break;

Default:

Console.WriteLine (―Invalid option. Please select S, M or L‖);

break;

}

Page 4: c# QBANK SOL (1)

Question Bank Solution for C#

4 | P a g e

If (cost! = 0)

Console.WriteLine (―Please pay {0} rupees‖, cost);

}

}

Q.4 Print the following triangle using Continue, Break and Goto statements.

*

**

***

****

*****

******

*******

********

*********

A. using System;

Class GotoLabel

{

Public static void Main ()

{

For ( int i=0; <100; i++)

{

Console.Writeline (― ―);

If (i>=10)

break;

For (int j=1; j<100; j++)

{

Console.Write (―*‖);

If (j==i)

goto loop1;

}

loop1: continue;

}

Console.WriteLine (―Terminate the Break‖);

}

}

Page 5: c# QBANK SOL (1)

Question Bank Solution for C#

5 | P a g e

Q.5 Write a program to convert the given Fahrenheit value to calcius where the values in Fahrenheit

range from 98.5 to 102. The values are incremented by 0.1.

A. using System;

class Test

{

public static void Main()

{

double f, c;

Console.WriteLine("Fahrenheit\t Celsius");

For (f = 98.5; f <= 102; f = f + 0.1)

{

c = (f - 32) / 1.8;

Console.WriteLine("{0:F2}\t{1:F2}",f , c);

}

Console.Read ();

}

}

Q.6 Display the sum of (1/5) + (3/6) +…. + (21/15).

A. Class Series

{

Public Static Void Main ()

{

Float i=1f, j=5f, s=0f;

Do

{

s= s+ (i/j);

i=i+2;

Page 6: c# QBANK SOL (1)

Question Bank Solution for C#

6 | P a g e

j++;

}

While (i<=21);

Console.WriteLine (―The sum of the series is {0}‖,s);

}

}

Q.7 Display the sum of (1) + (1+2) + (1+2+3) + …. + (1+2+3+4+5+6+7+8+9+10)

A. Class Series

{

Public Static Void Main ()

{

Int i, n=0, s=0;

For(x=1; x<=10; x++)

{

s= s+ x;

n=n+s;

}

Console.WriteLine (―The sum of the series is {0}‖, n);

}

}

Q.8 Display the sum of (1) + (1*2) + (1*2*3) + …. + (1*2*3*4*5*6*7*8*9*10)

A. Class Series

{

Public Static Void Main ()

{

Int i, n=1, s=0;

Page 7: c# QBANK SOL (1)

Question Bank Solution for C#

7 | P a g e

For(x=1; x<=10; x++)

{

n= n* x;

s=s+n;

}

Console.WriteLine (―The sum of the series is {0}‖, s);

}

}

Q.9 Initialize any three variables to values 5, 8, 9 respectively and display their values until second

variable becomes twice its value. Demonstrate using goto.

A. using System;

class Use_goto

{

public static void Main()

{

int i=5, j=8, k=9;

For (i=0; i < 20; i++)

{

For (j=0; j < 20; j++)

{

For (k=0; k < 20; k++)

{

Console.WriteLine ("i, j, k: " + i + " " + j + "

" + k);

If (j == (j*2))

goto stop;

}

}

}

stop:

Console.WriteLine ("Stopped! i, j, k: " + i + " " + j + " " + k);

}

} Q.10 Create a class InterestCalculator which allows user to select if he wants to calculate Simple

Interest or Compound Interest. Now based on formulas calculate SI or CI and display it in format

###. ##.SI=PNR/100 and CI=P*((R/100) + 1) to the power of period.

Page 8: c# QBANK SOL (1)

Question Bank Solution for C#

8 | P a g e

A. using System;

Class InterestCalculator

{

public static void Main()

{

Console.WriteLine (―----Interest Calculator----‖);

Console.WriteLine (―Calculate Simple (S)/Compound (C) Interest‖);

String choice=Console.ReadLine ();

Console.WriteLine (―Enter Principal Amount :-―);

double p= double.Parse(Console.ReadLine());

Console.WriteLine (―Enter Rate Of Interest:-―);

double r= double.Parse(Console.ReadLine());

Console.WriteLine (―Enter Duration:-―);

int t= Int32.Parse(Console.ReadLine());

If (choice== ―S‖)

{

double si=(double)((p*r*t)/100)

Console.WriteLine (―Simple Interest is: {0, 0: Rs ###, ##}‖, si);

}

Else

{

double ci=(double)p*(Math. Pow (((r/100) +1), t));

Console.WriteLine (―Compound Interest is: {0, 0: Rs ###, ##}‖, ci);

}

}

}

Q.11 Write a program to determine if a number is prime else display its largest factor.

A. using System;

Class FindPrimes

{

Public static void Main ()

{

int num;

int i;

int factor;

bool isprime;

For (num = 2; num < 20; num++)

{

isprime = true;

factor = 0;

// see if num is evenly divisible

For (i=2; i <= num/2; i++)

{

If ((num % i) == 0)

{

Page 9: c# QBANK SOL (1)

Question Bank Solution for C#

9 | P a g e

// num is evenly divisible -- not prime

isprime = false;

factor = i;

}

}

If (isprime)

Console.WriteLine (num + "is prime.");

Else

Console.WriteLine ("Largest factor of" + num +" is" + factor);

}

}

}

MANIPULATING STRINGS AND REGULAR EXPRESSIONS:

Q.12 Write a program that takes two inputs as string from users and copies the input of string2 to

string5 and checks for the string3 ends with ‗IDE‘ or not. The program shows true if the string3

ends with ‗IDE‘. Searches char ‗a‘ from string1. Inserts ‗hello‘ in the string6 at position 5 and

shows the string6.

A. using System;

Class Program

{

public void Display()

{

String str1=‖‖;

Console.WriteLine (―Enter a string: ‖);

str1=Console.Readline ();

String str2=‖‖;

Console.WriteLine (―Enter another string: ‖);

str2=Console.Readline ();

String str3=‖C# 2005 is developed in Visual studio 2005 IDE‖;

Console.WriteLine (―String str3: {0}‖,str3);

String str5=String.Copy(str2);

Console.WriteLine (―String str5: {0}‖,str5);

Console.WriteLine (―String str5 is {0} characters long‖,str5.Length);

If (str3.EndsWith(―IDE‖)==True)

Console.WriteLine (―True‖);

Else

Console.WriteLine (―False‖);

Console.WriteLine (―The first time a occurred in string str1 at

position:{0}‖,str1.IndexOf(―a‖)+1);

Page 10: c# QBANK SOL (1)

Question Bank Solution for C#

10 | P a g e

String str6=str2.Insert (5,‖Hello‖);

Console.WriteLine(―String str6: {0}‖,str6);

}

Static void Main ()

{

Program p=new Program ();

p.Display ();

}

}

Q.13 Create a program that accepts two string inputs from users and appends the first string to a

predefined value. Using String Builder class, a string value is inserted in the string. Then, all

spaces in the first string are replaced with * and the program calculates the length of the two

strings after appending.

A. using System;

Class StringBuilderExample

{

public void Show()

{

String str1=‖‖;

String str2=‖‖;

Console.Write (Enter the string: ‖);

str1=Console.ReadLine ();

Console.Write (―Enter next string: ‖);

str2=Console.ReadLine ();

StringBuilder b1=new StringBuilder (str1, 4);

StringBuilder b2=new StringBuilder (str2, 4);

int cap=b1.EnsureCapacity(55);

Console.Write (―String str1 appended to: ‖);

b1.Append (―This is a class Test‖);

Console.WriteLine (b1);

Page 11: c# QBANK SOL (1)

Question Bank Solution for C#

11 | P a g e

Console.Write (―String str2 inserted with: ‖);

b2.insert (2, ―String Builder‖);

Console.WriteLine (b2);

Console.Write(―Second character of string2 removed‖);

b2.Remove (2, 4);

Console.WriteLine (b2);

b1.Replace (‗‘, ‗*‘);

Console.WriteLine (―Spaces removed from string1‖);

Console.WriteLine (b2);

Console.Writeline (―Length of string1 is ‖,b1.Length.ToString());

Console.Writeline (―Length of string2 is ‖, b2.Length.ToString());

}

static void Main()

{

StringBuilderExample s=new StringBuilderExample ();

s.Show ();

}

}

Q.14 Write a program that takes two inputs as string from users and copies the input of string2 to

string4 by replacing its value and checks for length of string 4, checks for a word ‗development‘

in string3 and shows its position. It inserts ‗nice‘ in string10 at position 73 and then replaces

‗nice‘ word after ‗applications‘ word in string11.

A. using System;

Class program

{

Page 12: c# QBANK SOL (1)

Question Bank Solution for C#

12 | P a g e

public void Show()

{

String str1=‖‖;

String str2=‖‖;

Console.Write (Enter the string: ‖);

str1= Console.ReadLine ();

Console.Write (―Enter next string: ‖);

str2= Console.ReadLine ();

String str3=@‖C# 2005 is one of the core languages of .Net. It provides a custom

.Net platform for development of applications‖;

//the string copy method

String s4=String.Copy (str2);

Console.WriteLine (―string4 having value of string2‖+s4);

Console.Writeline (―Length of string4 is {0}‖, s4.Length);

Console.WriteLine (―The word development occurs first at position {0} in

string3‖, str3.IndexOf (―development‖) + 1);

String str10=str3.Insert (73,‖nice‖);

Console.WriteLine (―String10: {0}‖, str10);

String str11=str3.Insert (str3.IndexOf (―application‖), ―nice‖);

Console.WriteLine (―‖String11 is {0}\n‖, str11);

}

Static void Main ()

{

Program p=new Program ();

p.Display ();

}

Page 13: c# QBANK SOL (1)

Question Bank Solution for C#

13 | P a g e

}

Q.15 Accept 2 strings from user and check if the two string are equal using string method (case

sensitive).

A. using System;

Class StringEquivalence

{

Public Static Void Main ()

{

String str1, str2;

Console.WriteLine (―Enter string one :-----‖);

Str1=Console.ReadLine ();

Console.WriteLine (―Enter string two :-----‖);

Str2=Console.ReadLine ();

If (String.Compare (str1, str3, false) == 0)

Console.WriteLine (str1 + " and "+ str3 "); }

}

Q.16 Create a program which accepts a name from user. If the name has two consecutive identical

characters then display ‗Twin letters present‘ else display ‗No twin letters‘.

A. using System;

Class Twin

{

Public static void Main ()

{

bool flag;

String main;

Console.Write (―Enter a string‖);

main = Console.ReadLine ();

For (int i=0; i<main.Length; i++)

{

If (String.Compare (main.substring(i,1),main.substring(i+1,1)))

{

flag = 1;

Page 14: c# QBANK SOL (1)

Question Bank Solution for C#

14 | P a g e

Exit for;

}

}

If (flag=1)

Console.WriteLine (―Twin letters present‖);

Else

Console.WriteLine (―No Twin letters‖);

Console.Read ();

}

}

Q.17 Create a program that accepts a sentence from user and checks if its starts with ‗Th‘ and ends

with ‗ed‘ using regular expressions.

A. using System;

using System.Text.RegularExpression;

Class RegularExp

{

Public static void Main ()

{

String sentence;

sentence = Console.ReadLine();

If (Regex.IsMatch (sentence,‖[\bTh\s*ed]‖)==True)

Console.WriteLine (―The line starts with ‗Th‘ and ends ‗ed‘‖);

Else

Console.WriteLine (―Invalid sentence‖);

}

}

Q.18 If the pattern to be matched for an alphanumeric data is ‗^a-zA-Z‘ then write a program where the

user entered data is checked if it is alphanumeric using regular expressions.

A. using System;

using System.Text.RegularExpression;

Class RegularExp

{

Public static void Main ()

{

String s;

s = Console.ReadLine ();

If (Regex.IsMatch (sentence,‖[^a-zA-Z]‖)==True)

Console.WriteLine (―The string is alphanumeric‖);

Else

Page 15: c# QBANK SOL (1)

Question Bank Solution for C#

15 | P a g e

Console.WriteLine (―The string is not alphanumeric‖);

}

}

HANDLING ARRAY:

Q.19 Create an array list of 10 prime numbers and count the elements and capacity of arraylist. After

this, remove two elements from the start, count elements and again replace the two prime

numbers in the beginning of the array list.

A. using System;

Class Program

{

static void Main()

{

Arraylist a= new Arraylist();

Console.WriteLine (―Capacity of arraylist: ―+a.Capacity);

Console.WriteLine (―Elements of arraylist: ―+a.Count);

Console.Writeline ();

Console.WriteLine (―Adding ten prime numbers in arraylist‖);

a.Add(2);

a.Add(3);

a.Add(5);

a.Add(7);

a.Add(11);

a.Add(13);

a.Add(17);

a.Add(19);

a.Add(23);

a.Add(29);

Console.WriteLine (―Now Capacity of arraylist is: ―+a.Capacity);

Console.WriteLine (―Now Elements of arraylist: ―+a.Count);

Console.WriteLine (―Elements in arraylist are : ―);

For (int i=0; i<a.Count; a++)

Console.Write (a[i] +‖ ―);

Console.WriteLine (―removing 2 elements from the arraylist‖);

a.Remove(4);

a.Remove(9);

Console.WriteLine (―After removal Capacity of arraylist is:

―+a.Capacity);

Console.WriteLine (―After removal Elements of arraylist:

―+a.Count);

Console.WriteLine (―Elements in arraylist are: ―);

For each (int m in a)

Console.Write (a[i] +‖ ―);

Page 16: c# QBANK SOL (1)

Question Bank Solution for C#

16 | P a g e

Console.WriteLine (―Replacing first two elements in the arraylist with

prime numbers‖);

a [0]=31;

a [1]=37;

Console.WriteLine (―After replacing Elements in arraylist are:

―);

For each (int m in a)

Console.Write (a[i] +‖ ―);

}

}

Q.20 Create a string array, display the elements in the array and then display them in reverse order. Use

function to display the array elements. Another array having string elements is used to sort the

array elements alphabetically and then displays the reversed data.

A. Class Program

{

public static void ArrayDisplay()

{

foreach (String str in a)

{

Console.WriteLine (―Value: {0}‖,str);

}

Console.WriteLine (―\n‖);

}

static void Main()

{

String [] a = {‖John‖, ‖Norman‖, ‖Greg‖, ‖Steve‖, ‖Victor‖, ‖Logan‖};

ArrayDisplay (a);

Array.Reverse (a);

Console.WriteLine (―Reversed Array‖);

ArrayDisplay (a);

String []b= {―This ‖,‖is ‖, ‖an ‖, ‖example ‖, ‖of ‖, ‖array list ‖, ‖sorting

‖, ‖alphabetically ‖};

ArrayDisplay (b);

Console.WriteLine (―Array sorted in alphabetical order‖);

Array.Sort (b);

ArrayDisplay (b);

}

}

Q.21 Create a class MatTranspose. Write a program to print the transpose a matrix.

A. using System;

Class MatTranspose

Page 17: c# QBANK SOL (1)

Question Bank Solution for C#

17 | P a g e

{

public static void Main()

{

int i, j, k, m, n;

int [,] matrix = new int[3, 3];

Console.Write ("Enter the matrix: \n\n");

For (i=0; i<3; ++i)

{

Console.WriteLine ("Enter {0} row:", (i+1));

For (j=0; j<3; ++j)

Console.ReadLine (matrix[i] [j]);

}

Console.Write ("\n\n");

For (j=0; j<3; ++j)

{

For (i=0; i<3; ++i)

{

If (i > j)

Swap (ref matrix[i] [j], ref matrix[j] [i]);

}

}

Console.Write ("The transposed matrix is: \n\n");

For (i=0; i<3; ++i)

{

For (j=0; j<3;++j)

Console.WriteLine (matrix[i] [j]);

Page 18: c# QBANK SOL (1)

Question Bank Solution for C#

18 | P a g e

}

}

public void swap(ref int x, ref int y)

{

int t=x;

x=y;

y=t;

return;

}

}

Q.22 Write program to print 4 5 6 7

4 5 6

4 5 6 7 8 (use jagged arrays)

A. using System;

class Jagged

{

public static void Main()

{

int[][] jagged = new int[3][];

jagged[0] = new int[4];

jagged[1] = new int[3];

jagged[2] = new int[5];

int i;

// store values in first array

for(i=4; i < 8; i++)

jagged[0][i] = i;

// store values in second array

for(i=4; i < 7; i++)

jagged[1][i] = i;

// store values in third array

for(i=4; i < 9; i++)

Page 19: c# QBANK SOL (1)

Question Bank Solution for C#

19 | P a g e

jagged[2][i] = i;

// display values in first array

for(i=4; i < 8; i++)

Console.Write(jagged[0][i] + " ");

Console.WriteLine();

// display values in second array

for(i=4; i < 7; i++)

Console.Write(jagged[1][i] + " ");

Console.WriteLine();

// display values in third array

for(i=4; i < 9; i++)

Console.Write(jagged[2][i] + " ");

Console.WriteLine();

}

}

Q.23 Write a program to display the digits of an integer using words.

A. using System;

Class ConvertDigitsToWords

{

Public static void Main ()

{

int num;

int nextdigit;

int numdigits;

int [] n = new int[20];

string [] digits = { "zero", "one", "two","three", "four", "five",

"six", "seven", "eight","nine" };

num = 1908;

Console.WriteLine ("Number: " + num);

Console.Write ("Number in words: ");

nextdigit = 0;

numdigits = 0;

/* Get individual digits and store in n.

These digits are stored in reverse order. */

do

{

Page 20: c# QBANK SOL (1)

Question Bank Solution for C#

20 | P a g e

nextdigit = num % 10;

n[numdigits] = nextdigit;

numdigits++;

num = num / 10;

}

while (num > 0);

numdigits--;

// display words

For (; numdigits >= 0; numdigits--)

Console.Write (digits [n [numdigits]] + " ");

Console.WriteLine ();

}

}

Q.24 An array contains 5 names: James, Smith, Thomas, Serena, Janet. Write a program that helps

search the name Thomas from the array using For Each loop.

A. using System;

class Search

{

public static void Main()

{

String[] names = new String[10];

bool found = false;

// give names some values

names [0] = ―James‖;

names [1] = ―Smith‖;

names [2] = ―Thomas‖;

names [3] = ―Serena‖;

names [4] = ―Janet‖;

// use foreach to search names for key

foreach(int x in names)

{

If (x == names [2])

{

found = true;

break;

}

}

If (found)

Console.WriteLine("Value found!");

}

}

Q.25 Accept 10 numbers from the user, store them in an array and display them in ascending order.

A. using System;

Page 21: c# QBANK SOL (1)

Question Bank Solution for C#

21 | P a g e

Class ArrayTest

{

Public Static Void Main ()

{

int num [10], n, i=0, j=0;

Console.WriteLine(―Enter 10 numbers‖);

While (i<10)

{

Console.ReadLine(num[i++])

}

For (i=1; i<10; i++)

{

For (j=1; j<10; j++)

{

If (num [j-1]>num [j])

{

n=num [j-1];

num [j-1]=num [j];

num [j]=n;

}

}

}

Console.WriteLine(―Sorted List‖);

For (i=1; i<10; i++)

Console.WriteLine(num[i]);

}

Page 22: c# QBANK SOL (1)

Question Bank Solution for C#

22 | P a g e

}

Q.26 Write a program to allow the user to specify any two rows of matrix and then change the matrix

to display the row values swapped.

A. using System;

class Test

{

public static void Main()

{

int[,] x = new int[3, 3];

int fr, sr, temp,i,j;

for(i=0;i<3;i++)

{

For(j=o;j<3;j++)

{

X[i,j]=Console.ReadLine();

}

}

Console.WriteLine ("Original Values ");

For (i = 0; i < 3; i++)

{

For (j = 0; j < 3; j++)

{

Console.Write(x [i, j] + " ");

}

Console.WriteLine ();

}

Console.Write ("Enter First Row -->");

Page 23: c# QBANK SOL (1)

Question Bank Solution for C#

23 | P a g e

fr = int.Parse(Console.ReadLine());

Console.Write ("Enter Second Row -->");

sr = int.Parse(Console.ReadLine());

//Procedure for Swapping

for (i = 0; i < 3; i++)

{

temp = x[fr, i];

x[fr, i] = x[sr,i];

x[sr, i] = temp;

}

Console.WriteLine("Displaying Swapped Values");

for (i = 0; i < 3; i++)

{

for (j = 0; j < 3; j++)

{

Console.Write(x[i, j] + " ");

}

Console.WriteLine();

}

Console.Read();

}

}

METHODS IN C#:

Q.27 Overload a function repchar to display + + +

= = = =

> > > > >

A. Class display

{

Page 24: c# QBANK SOL (1)

Question Bank Solution for C#

24 | P a g e

Public void repchar ()

{

int i;

For (i=0; i<=3; i++)

Console.Write (―+ ‖);

Console.Write (―\n‖);

}

Public void repchar (char a)

{

int i;

For (i=0; i<=4; i++)

Console.Write (a+ ― ―);

Console.Write (―\n‖);

}

Public void repchar (char a, int x)

{

int i;

For (i=0; i<=x; i++)

Console.Write (a + ― ―);

Console.Write (―\n‖);

}

}

Class Test

{

Public static voidMain ()

{

Display d=new Display ();

Console.Write (d.repchar ());

Console.Write (d.repchar (‗=‘));

Console.Write (d.repchar (‗>‘, 5));

}

}

Q.28 Write a method that would calculate the value of money for a given period of years and print the

result giving following details on one line of output:- Principal Amount, Interest Rate, Period in

Years, Final value. The method takes principal amount, rate of interest and period as input and

does not return any value.

value at the end of the year= value at start of the year * (1 + interest rate).Write program to test

the method.

A. using System;

Class Interest

{

Public static void Main ()

{

int numyears;

double principal, rate;

Console.WriteLine (―Enter the principal amount, rate of interest and period‖);

numyears = int.Parse (Console.ReadLine ());

principal = double.Parse (Console.ReadLine ());

Page 25: c# QBANK SOL (1)

Question Bank Solution for C#

25 | P a g e

rate = double.Parse (Console.ReadLine ());

callinterest (principal, rate, numyears);

Console.Read ();

}

Public void callinterest (double p, double r, int n)

{

double final;

r=r/100;

For (int i=1; i<=n; i++)

{

final=p* (1+r);

Console.Write (p+ ― ,―+r+‖ , ―+i+‖ , ―+final);

p=final;

}

}

}

Q.29 Write a program to display a string in reverse using recursion.

A. using System;

class RevStr

{

// Display a string backwards.

public void displayRev(string str)

{

if(str.Length > 0)

displayRev(str.Substring(1, str.Length-1));

else

return;

Console.Write(str[0]);

}

}

class RevStrDemo

{

public static void Main()

{

string s = "this is a test";

RevStr rsOb = new RevStr();

Console.WriteLine("Original string: " + s);

Console.Write("Reversed string: ");

rsOb.displayRev(s);

Console.WriteLine();

}

}

Page 26: c# QBANK SOL (1)

Question Bank Solution for C#

26 | P a g e

Q.30 Create a ChkNum class that contains 2 methods:

i. isPrime returns true if number is prime else false

ii. leastComFactor that returns the smallest factor that its two arguments have in common.

Demonstrate the two methods in ParameterDemo Class.

A. using System;

class ChkNum

{

// Return true if x is prime.

public bool isPrime(int x)

{

For (int i=2; i <= x/i; i++)

If ((x %i) == 0)

return false;

return true;

}

// Return the least common factor.

public int leastComFactor(int a, int b)

{

int max;

if(isPrime(a) | isPrime(b)) return 1;

max = a < b ? a : b;

for(int i=2; i <= max/2; i++)

if(((a%i) == 0) & ((b%i) == 0))

return i;

return 1;

}

}

class ParmDemo

{

public static void Main()

{

ChkNum ob = new ChkNum ();

int a, b;

For (int i=1; i < 10; i++)

If (ob.isPrime (i))

Console.WriteLine (i + " is prime.");

Else

Console.WriteLine (i + " is not prime.");

Console.WriteLine (―Enter first number to find their Least Common Factor:----‖);

a = Console.ReadLine ();

Console.WriteLine (―Enter first number to find their Least Common Factor:----‖);

b = Console.ReadLine ();

Page 27: c# QBANK SOL (1)

Question Bank Solution for C#

27 | P a g e

Console.WriteLine ("Least common factor for " +a + " and " + b + " is " +

ob.leastComFactor (a, b));

}

}

Q.31 Create a class TestOut having a static method FillArray which takes an out type of array as

argument and initializes the elements in the array. In the main, an array should be passed to the

function and the elements should be displayed. Keep the console window open in debug mode

until user presses some key.

A. class TestOut

{

static void FillArray(out int[] arr)

{

// Initialize the array:

arr = new int[5] { 1, 2, 3, 4, 5 };

}

static void Main()

{

int[] theArray; // Initialization is not required

// Pass the array to the callee using out:

FillArray (out theArray);

// Display the array elements:

System.Console.WriteLine ("Array elements are: ");

For (int i = 0; i < theArray.Length; i++)

{

System.Console.Write (theArray[i] + " ");

}

// Keep the console window open in debug mode.

System.Console.WriteLine ("Press any key to exit.");

Page 28: c# QBANK SOL (1)

Question Bank Solution for C#

28 | P a g e

System.Console.ReadKey ();

}

}

Q.32 Using the concept of variable number of parameters being passed to a single method, write a

program that calculates the average of any set of numbers passed as parameters to the method

avgVal () belonging to the class Avg.Display bthe calculated value in the Main of the class

ParamsExample (check the method by passing two, three and six parameters and then by passing

an integer array).

A. using System;

Class Avg

{

public int avgVal(params int[] intdata)

{

int sum=0, avg=0;

If (intdata.Length == 0)

{

Console.Writeline(―Error: no arguments‖);

return 0;

}

For (int i=0; i<intdata.Length; i++)

{

sum= sum+ intdata[i];

}

avg= sum/intdata.Length;

return avg;

}

}

public class ParamsExample

{

public static void Main()

{

Avg a=new Avg();

int avg;

int num1=50, num2=60;

//calling the average function using 2 parameters

avg=a.avgVal(num1, num2);

Console.Writeline(―Average of two numbers is: {0}‖,avg);

//calling the average function using 3 parameters

avg=a.avgVal(num1, num2, 180);

Console.Writeline(―Average of three numbers is: {0}‖,avg);

//calling the average function using 6 parameters

avg=a.avgVal(num1, num2,23, 57, 89,90);

Console.Writeline(―Average of six numbers is: {0}‖,avg);

Page 29: c# QBANK SOL (1)

Question Bank Solution for C#

29 | P a g e

//calling the average function using an integer array

int [] i={12,15,34,87,53,65,29,30};

avg=a.avgVal(i);

Console.Writeline(―Average of numbers in the array is: {0}‖ ,avg);

}

}

Q.33 Create a class TaxCalc that 4 methods named TaxCalulator:-

i. takes 2 amount values and 2 rate values and returns taxable amount

ii. takes 1 amount value and 1 rate value and returns taxable amount

iii. takes 1 amount value, assigns rate as 12% and returns taxable amount

iv. takes Tax Type (string) as argument and return the rate. Tax Type can be Personal with

rate 10%

A class Checktax with main which checks if the user has a house registered I his name or has a

business or owns both. If he has house owned then input house rate and house value from user to

display the taxable amount. If he has business the input gross sales and rate of tax on gross sales

to calculate his taxable amount. If he owns both then calculate tax on both assets. Calculate the

total tax by adding his total earning that he inputs for all categories. Display his Personal tax rate

also.

A. using System;

Class TaxCalc

{

//method with 4 arguments

public double TaxCalculator (double amt1, double rate1,double amt2,double rate2)

{

double taxamt=(amt1*rate1)+ (amt2*rate2); return taxamt;

}

public double TaxCalculator (double amt, double rate)

{

double taxamt=amt*rate; return taxamt;

}

public double TaxCalculator (double amt)

{

double rate=0.12;

double taxamt=amt*rate; return taxamt;

}

public double TaxCalculator (string taxtype)

{

double taxrate=0;

If (taxtype== ―Personal‖)

taxrate = 0.10;

return taxrate;

}

}

Class Checktax

Page 30: c# QBANK SOL (1)

Question Bank Solution for C#

30 | P a g e

{

public static void Main()

{

string userresponse;

bool flaghome=false;

bool flagbusiness=false;

double houserate=0;

double housevalue=0;

double grosssales=0;

double taxrate=0;

double earning=0;

double totaltax=0;

TaxCalc t=new TaxCalc ();

Console.WriteLine (―Which do u own for yourself :‖);

Console.WriteLine (―Press h: House‖);

Console.WriteLine (―Press b: Business‖);

Console.WriteLine (―Press hb: Both‖);

userresponse = Console.ReadLine();

If (userresponse == ―h‖)

{

flaghome = true;

Console.WriteLine (―Enter the value of your house‖);

housevalue= double.Parse(Console.ReadLine());

Console.WriteLine (―Enter the tax rate of your house‖);

houserate = double.Parse(Console.ReadLine());

totaltax =t. TaxCalculator (housevalue, houserate);

}

Else If (userresponse == ―b‖)

{

flagbusiness = true;

Console.WriteLine (―Enter the gross sales of business‖);

grosssales= double.Parse(Console.ReadLine());

Console.WriteLine (―Enter the tax rate on gross sales‖);

taxrate = double.Parse(Console.ReadLine());

totaltax =t. TaxCalculator (grosssales, taxrate);

}

Else If (userresponse ==‖hb‖)

{

flaghouse = true;

flagbusiness = true;

total tax=t.TaxCalculator(housevalue, houserate, grosssales,

taxrate)

}

Console.WriteLine (―Enter the total earnings for the year in Rupees‖);

earning = double.Parse (Console.WriteLine());

totaltax = totaltax+t.TaxCalculator (earning);

Page 31: c# QBANK SOL (1)

Question Bank Solution for C#

31 | P a g e

Console.WriteLine(―‘Your total tax calculated is {0}‖, totaltax);

Console.WriteLine (―The Personal tax rate is {0}‖, t.TaxCalculator

(―Personal‖));

}

}

STRUCTURES AND ENUMERATIONS:

Q.34 Create enumeration for Degree having elements: Mechanical=1, Electronics, Electricals,

Aeronautics, Civil. A class Select initializes the enum object with default and parameterized

constructors. A class GetDetails has five data members: name, address, telephone, course, fees.

The degree is specified by select class object. There are two methods:

i. GetAdmission that accepts the user choice for the degree

ii. GetStudentDetails that accepts student details

A class StudentMenu shows the degree for which the student got admission along with his details

and also displays a message of format:-

―Thank you shreyas for getting admission in Electronics course‖

A. using System;

public enum Degree

{

Mechanical=1, Electrical, Electronics, Aeronautics, Civil

}

Class Select

{

public Degree degree;

public Select

{

degree= Degree.Civil;

}

public Select (Degree degree)

{

Page 32: c# QBANK SOL (1)

Question Bank Solution for C#

32 | P a g e

degree=Degree.Civil;

}

}

Class GetDetails

{

Select degree;

String name, address, telephone, course, fees;

public GetDetails ()

{

degree=new Select();

}

public void GetAdmission ()

{

int c=0;

Console.Writeline (―Enter the couse to take admission‖);

Console.WriteLine(―1. Mechanical‖);

Console.WriteLine(―2. Electrical‖);

Console.WriteLine(―3. Electronics‖);

Console.WriteLine(―4. Aeronautics‖);

Console.WriteLine (―5. Civil‖);

Console.Write (―Plz enter ur choice: ‖);

c=Console.ReadLine();

Switch(c)

{

case 1:

Page 33: c# QBANK SOL (1)

Question Bank Solution for C#

33 | P a g e

degree.degree= Degree.Mechanical; break;

case 2:

degree.degree= Degree. Electrical; break;

case 3:

degree.degree= Degree. Electronics; break;

case 4:

degree.degree= Degree. Aeronautics; break;

default:

degree.degree= Degree. Civil; break;

}

}

Public void GetStudentDetails ()

{

Console.Write (―Enter name‖);

name = Console.ReadLine();

Console.Write(―Enter address‖);

address = Console.ReadLine();

Console.Write(―Enter telephone number‖);

telephone = Console.ReadLine();

Console.Write(―Enter course‖);

course = Console.ReadLine();

Console.Write(―Enter the fees‖);

fees = Console.ReadLine();

}

}

Page 34: c# QBANK SOL (1)

Question Bank Solution for C#

34 | P a g e

Class StudentMenu

{

public static void Main()

{

GetDetails gd= new GetDetails ();

gd.GetAdmission ();

Console.WriteLine ();

gd.GetStudentDetails ();

Console.WriteLine ();

Console.WriteLine (―Thank You ―+gd.name+‖for taking admission

in‖+gd.course+‖course‖);

}

}

Q.35 Create two enumerations: Staff and Company. The elements of Staff are:- Directors, Managers,

Executives. The elements of Company are:- RIL, IDFC, TechnoSoft Inc. The program should

display the data contained in Staff and Company enumerations.

A. using System;

enum Staff

{

Directors, Managers, Executives

}

enum Company

{

RIL, IDFC, TechnoSoft Inc

}

Class program

{

Public static void ShowStaff (Staff st)

{

Switch (st)

{

Case Staff.Directors:

Console.WriteLine (―You are a Director‖);

Break;

Case Staff.Managers:

Console.WriteLine (―You are a Manager‖);

Break;

Case Staff.Executives:

Console.WriteLine (―You are an Executive‖);

Break;

Default: Break;

}

}

Public static void ShowCompany (Company sc)

{

Switch (sc)

{

Case Company.RIL:

Page 35: c# QBANK SOL (1)

Question Bank Solution for C#

35 | P a g e

Console.WriteLine (―RIL‖);

Break;

Case Company.IDFC:

Console.WriteLine (―IDFC‖);

Break;

Case Company.TechnoSoftInc:

Console.WriteLine (―TechnoSoft Inc‖);

Break;

Default: Break;

}

}

Static void Main ()

{

Staff st=Staff.Directors;

Console.WriteLine (―This is an example of Enumeration in c#‖);

ShowStaff(st);

Company c=Company.TechnoSoft Inc;

Console.WriteLine (―Director belongs to Company: ‖);

ShowCompany (c);

}

}

Q.36 Create a structure Employee having one data member: emp_details. Create property Write to

assign and return the value of emp_details and method Read that accepts user input respectively.

Create another structure EmployeeDetails that has data members: name, address, telephone, dept

and salary of the type Employee. Create properties for the data members. The ShowAllDetails ()

method accepts all the employee details. A class ShowEmployee details displays the data

accepted from user in a systematic manner in its Main ().

A. using System;

Public struct Employee

{

private string emp_details;

public string Write

{

get { return emp_details; }

set { emp_details=value; }

}

Public string Read ()

{

return Console.ReadLine ();

}

}

Public struct EmployeeDetails

{

Employee name;

Employee address;

Employee telephone;

Employee department;

Page 36: c# QBANK SOL (1)

Question Bank Solution for C#

36 | P a g e

Employee salary;

public Employee Name

{

get { return name; }

set { name= value; }

}

public Employee Address

{

get { return address; }

set { address = value; }

}

public Employee Telephone

{

get { return telephone; }

set { telephone = value; }

}

public Employee Department

{

get { return department; }

set { department = value; }

}

public Employee Salary

{

get { return salary; }

set { salary = value; }

}

public void ShowAllDetails()

{

Employee e= new Employee ();

Console.WriteLine (Enter the name of the employee);

name.Write=e.Read ();

Console.WriteLine(Enter the address of the employee);

address.Write=e.Read ();

Console.WriteLine(Enter the telephone of the employee);

telephone.Write=e.Read ();

Console.WriteLine (Enter the department of the employee);

department.Write=e.Read ();

Console.WriteLine(Enter the salary of the employee);

salary.Write=e.Read ();

}

}

Class ShowEmployeeDetails

{

Static void Main ()

{

string input=‖‖;

EmployeeDetails e=new EmployeeDetails ();

e.ShowAllDetails();

Console.WriteLine ();

Page 37: c# QBANK SOL (1)

Question Bank Solution for C#

37 | P a g e

Console.WriteLine (―Showing Employee Details‖);

Console.WriteLine (―---------------------------------‖);

Console.WriteLine (―Name: {0}‖,e.Name.Write);

Console.WriteLine (―Address: {0}‖,e.Address.Write);

Console.WriteLine (―Telephone: {0}‖,e.Telephone.Write);

Console.WriteLine (―Department: {0}‖,e.Department.Write);

Console.WriteLine (―Salary: {0}‖,e.Salary.Write);

Console.WriteLine (―Press y to save the record‖);

input =Console.ReadLine();

If (input == ―y‖)

Console.WriteLine (―Record saved‖);

Else

Console.WriteLine (―Record saved‖);

}

}

Q.37 Create a structure that contains a class school and another structure teachers. The structure

student has 2 data members: student name and roll number. Create properties for both and a show

method that displays them. The class school has 2 data members: school name, class name.

Create properties for both and a method show_details to display them. The structure teachers

having 2 members: teacher code and teacher name. Create a getvalues method to assign values for

members and a show method to display them. Now, assign and display the values for student

name, roll number, school, class, teacher identification and name.

A. using System;

struct student

{

Public string studentname;

Public string rollno;

//property for roll number

Public string Rollno

{

set {rollno=value;}

get {return rollno;}

}

//property for student name

Public string Name

{

set { name =value;}

get {return name;}

}

Class school

{

Public string schoolname;

Public string classname;

Page 38: c# QBANK SOL (1)

Question Bank Solution for C#

38 | P a g e

Public string SchoolName

{

set { schoolname =value;}

get {return schoolname;}

}

Public string ClassName

{

set { classname =value;}

get {return classname;}

}

Public void show_details ()

{

Console.WriteLine (―‘Schoolname: ―+ schoolname);

Console.WriteLine (―‘Schoolname: ―+ classname);

}

}

Public struct teachers

{

Public string tcode;

Public string tname;

Public void Getvalues (string code, string name)

{

tcode = code;

tname = name;

}

Public void show ()

{

Console.WriteLine(―‖Teacher‘s Code: ―+ tcode);

Console.WriteLine(―‖Teacher‘s Name: ―+ tname);

}

}

Public void Show ()

{

Console.WriteLine (―‖Student Name: ―+ studentname);

Console.WriteLine (―‖Student Rollno: ―+ rollno);

}

}

}

Class Program

{

Public static void Main ()

{

student st=new student ();

st.studentname=‖Shreyas‖;

st.rollno=‖9546‖;

st.Show ();

Page 39: c# QBANK SOL (1)

Question Bank Solution for C#

39 | P a g e

student.teachers t=new student.teachers ();

t.tcode=‖T16‖;

t.tname=‖Shilpa Rao‖;

t.show ();

t.getvalues (―T15‖,‖Abhay More‖);

t.show ();

student.school sc= new student.school();

sc.SchoolName=‖St. Johns School, Janakpuri, Delhi‖;

sc.ClassName=‖Vth‖;

sc.show_details();

}

}

Q.38 Create an enumerator that stores the values of languages: English=1, Hindi, Spanish, Dutch,

Marathi, Persian, German, French. Add these values to ArrayList and display it along with its

integer value.

A. using System;

using System.Collections;

enum languages

{ English=1,Hindi,Spanish, Dutch, Marathi, Persian, German, French }

class Test

{

public static void Main()

{

ArrayList a = new ArrayList ();

a.Add (languages.English);

a.Add (languages.Hindi);

a.Add (languages.Spanish);

a.Add (languages.Dutch);

a.Add (languages.Marathi);

a.Add (languages.Persian);

a.Add (languages.German);

Page 40: c# QBANK SOL (1)

Question Bank Solution for C#

40 | P a g e

a.Add (languages.French);

foreach (int i in a)

{

Console.WriteLine (" {0} {1}", i, (languages) i);

}

Console.Read ();

}

}

BOXING AND UNBOXING:

Q.39 Create a class BoxingDemo with a main method that accepts an integer from user and displays

the square of the number by boxing it to Object type. The boxing function must be performed by

static function Sqr returning integer value.

A. using System;

class BoxingDemo

{

public static void Main()

{

int x;

x = 10;

Console.WriteLine ("Here is x: " + x);

// x is automatically boxed when passed to sqr ()

x = BoxingDemo.sqr(x);

Console.WriteLine ("Here is x squared: " + x);

}

static int sqr(object o)

{

return (int)o * (int)o;

}

}

CLASSES AND OBJECTS:

Q.40 Design a class to represent a bank account. Include the following members;

Page 41: c# QBANK SOL (1)

Question Bank Solution for C#

41 | P a g e

Data Members:

i. Name of the depositor

ii. Account number

iii. Type of account

iv. Balance amount in the account

Methods:

i. To assign initial values

ii. To deposit an amount

iii. To withdraw an amount after checking balance

iv. To display the name and balance

A. Class Account

{

String name;

Double bal;

String acno;

String actype;

Public void assign (String n, String num, String t, double b)

{

name = n; acno=num; actype= t; bal= b;

}

Public void deposit (double amt)

{

bal =bal+amt;

Console.WriteLine (name +― your balance after deposit is ‖+bal)

}

Public void withdraw (double amt)

{

If (amt<= bal)

{

Page 42: c# QBANK SOL (1)

Question Bank Solution for C#

42 | P a g e

bal =bal-amt;

Console.WriteLine (name +― your balance after withdrawal is ‖+bal);

}

Else

{

Console.WriteLine (― Not enough balance to withdraw‖);

}

}

Public void Show ()

{

Console.Write (Account Holder\tAccountNumber\t AccountType\tBalance);

Console.WriteLine (―{0}\t {1}\t {2}\t {3}‖, name, acno, actype, bal);

}

}

Class program

{

Public Static void Main ()

{

Account a= new Account ();

a.assign (―Shreyas‖, ―124325G53‖, ―Savings‖, 20000);

a.Deposit (255.076);

a.Show ();

a.Withdraw (158.127);

a.Show ();

}

}

Page 43: c# QBANK SOL (1)

Question Bank Solution for C#

43 | P a g e

Q.41 Create a class PwrOfTwo that contains a method pwr returning power of two from 0 to 15. There

is an indexer which returns the powers of 2 in its get accessor (has no set accessor). In the class

UsePwrOfTwo containing the main method the first 8 powers of 2

A. using System;

class PwrOfTwo

{

/* Access a logical array that contains the powersof 2 from 0 to 15.*/

public int this[int index]

{

// Compute and return power of 2.

get

{

If ((index >= 0) && (index < 16)) return pwr(index);

Else return -1;

}

// there is no set accessor

}

int pwr(int p)

{

int result = 1;

For (int i=0; i < p; i++)

@@@@@@@@@@@@ result *= 2;

return result;

}

}

class UsePwrOfTwo

{

public static void Main()

{

PwrOfTwo pwr = new PwrOfTwo();

Console.Write("First 8 powers of 2: ");

for(int i=0; i < 8; i++)

Console.Write(pwr[i] + " ");

Console.WriteLine();

Console.Write ("Here are some errors: ");

Console.Write (pwr[-1] + " " + pwr[17]);

Console.WriteLine();

}

}

Q.42 Create a class Building with three members: floors, area, occupants. Add two methods:

i. one to calculate area per person

Page 44: c# QBANK SOL (1)

Question Bank Solution for C#

44 | P a g e

ii. second that returns maximum number of occupants if each should have minimum area.

Create two objects house and office and demonstrate the methods.

A. using System;

class Building

{

public int floors; // number of floors

public int area; // total square footage of building

public int occupants; // number of occupants

// Return the area per person.

public int areaPerPerson() { return area / occupants; }

/* Return the maximum number of occupants if each

is to have at least the specified minimum area. */

public int maxOccupant(int minArea) { return area / minArea; }

}

class BuildingDemo

{

public static void Main()

{

Building house = new Building ();

Building office = new Building ();

// assign values to fields in house

house.occupants = 4;

house.area = 2500;

house.floors = 2;

// assign values to fields in office

office.occupants = 25;

office.area = 4200;

office.floors = 3;

Console.WriteLine ("Maximum occupants for house if each has" +

300 + " square feet: " + house.maxOccupant (300));

Console.WriteLine ("Maximum occupants for office if each has" +

300 + " square feet: " + office.maxOccupant (300));

}

}

Q.43 Create a class Destruct with one integer data member. Add a method generator that creates an

object that is immediately destroyed. Create 100000 objects that should be destroyed.

A. using System;

class Destruct

{

public int x;

public Destruct(int i) { x = i; }

Page 45: c# QBANK SOL (1)

Question Bank Solution for C#

45 | P a g e

// called when object is recycled

~Destruct()

{

Console.WriteLine("Destructing " + x);

}

// generates an object that is immediately destroyed

public void generator(int i)

{

Destruct o = new Destruct(i);

}

}

class DestructDemo

{

public static void Main()

{

int count;

Destruct ob = new Destruct(0);

for(count=1; count < 100000; count++)

ob.generator(count);

Console.WriteLine("Done");

}

}

Q.44 Create a class Test that contains two data members: number1, number2. Create methods to find

LCM and GCD of any two numbers. Implement the function in a class called Testlcmgcd.

A. using System;

Class Test

{

int number1;

int number2;

int lcm(int a,int b)

{

int n;

For (n=1; ; n++)

{

If (n%a == 0 && n%b == 0)

return n;

}

}

int gcd(int a,int b)

{

int c;

while (1)

{

Page 46: c# QBANK SOL (1)

Question Bank Solution for C#

46 | P a g e

c = a%b;

If (c==0)

return b;

a = b;

b = c;

}

}

}

Class Testlcmgcd

{

public static void Main ()

{

int x, y;

int lcm, gcd;

Test t=new Test ();

//find the lcm of given numbers

Console.WriteLine (―Enter numbers to find the LCM of them :----‖);

x=Console.ReadLine ();

y=Console.ReadLine ();

lcm= t.lcm(x, y);

Console.Write (―The Lcm of {0} and {1} is {2}‖, x, y, lcm);

Console.WriteLine ();

//find the gcd of given numbers

Console.WriteLine (―Enter numbers to find the GCD of them :----‖);

x=Console.ReadLine ();

y=Console.ReadLine ();

If(x>y)

gcd=t.gcd(x,y);

Console.Write (―The Gcd of {0} and {1} is {2}‖, x, y, gcd);

Else

Console.Write (Plz enter first number grater than the second);

}

}

Q.45 Write a Program that accepts student marks in five subjects and display the following:

i. Student marks

ii. Total marks of each students

iii. Calculate and display the Maximum marks

iv. Calculate and display the Minimum marks

v. Calculate and display the Percentage of each student

A. using System;

Class StudentMarks

Page 47: c# QBANK SOL (1)

Question Bank Solution for C#

47 | P a g e

{

Static void Main ()

{

int []m= new int[5];

int totalmks=0;

Console.WriteLine(―Student information\n‖);

For (int i=0; i<5; i++)

{

Console.WriteLine(―Enter Your Marks in Subject {0}: ‖, i+1);

m [i]=int.Parse(Console.ReadLine());

}

Console.WriteLine();

//displaying student marks

Console.Writeline(―The marks u have entered are: ‖);

For (int i=0; i<5; i++)

{

If (i<4)

Console.Write (m[i] + ― , ‖);

Else

Console.Write (m[i]);

}

//Calculating and displaying total marks of the student

For (int i=0; i<5; i++)

{

totalmks= totalmks+m[i];

}

Console.WriteLine ();

Console.Write (―ur total marks are: {0}‖, totalmks);

//calculating and displaying maximum marks of the student

int maxmks=m[0];

int index=1;

For (int i=1; i<m.Length; i++)

{

If (m[i] > maxmks)

{

maxmks = m[i];

index = i+1;

}

}

Console.WriteLine(―You have scored maximum marks {0} in subject

{1}‖, maxmks, index);

//calculating and displaying minimum marks of the student

int minmks=m[0];

int index=1;

For (int i=1; i<m.Length; i++)

{

If (m[i] < minmks)

Page 48: c# QBANK SOL (1)

Question Bank Solution for C#

48 | P a g e

{

minmks = m[i];

index = i+1;

}

}

Console.WriteLine(―You have scored minimum marks {0} in subject

{1}‖, minmks, index);

//calculating and displaying Percentage of the student

double per;

double val=0.0;

val=(double)totalmks/500;

per=(double)val*100;

Console.WriteLine(―Your percentage is : {0}%‖, per);

}

}

INHERITANCE AND POLYMORPHISM:

Q.46 Create a class student having id and name as data members. Include constructor to assign values

to them and a method to display. Also include getdata method that accepts values for name and id

of student. A class Marks should store the marks of three subjects of the students and also their

name and id. The class marks should implement containment inheritance where the getdata

method of Marks class should also adk user to enter student name and id along with marks. The

marks of the student should be displayed.

A. using System;

Class Student

{

int id;

String name;

Public student (int i, string n)

{

id=i; name=n;

}

Public void getdata ()

{

Console.WriteLine (―Enter name :--‖);

id =Console.ReadLine();

Console.WriteLine (―Enter Id :--‖);

name =Console.ReadLine();

}

Public void Display ()

{

Console.WriteLine (―Name :- {0}\tId :-- {1}‖,name, id);

}

}

Class Marks

{

int []m=new int[3];

Page 49: c# QBANK SOL (1)

Question Bank Solution for C#

49 | P a g e

Student s=new Student ();

Public Marks (int a, int b, int c)

{

m[0]=a; m [1]=b; m [2]=c;

}

Public void getdata ()

{

s.getdata ();

Console.WriteLine (―Enter marks :---‖);

For (int i=0; i<3; i++)

m [i] = Console.ReadLine();

}

Public void Display ()

{

s.Display ();

Console.WriteLine (―Marks:-- {0}\t{1}\t{2}‖, m[0], m[1], m[2]);

}

}

Class Program

{

Public static void Main ()

{

Marks m=new Marks ();

m.getdata ();

m.Display ();

}

}

Q.47 Create a class Dept1 that has a single member salary that should be accessible by only the next

derived class. Define a method eSal that assigns salary a value.Now create another class Dept2

that inherits Dept1 adding 2 new members bonus and total salary. The constructor of this class

should initialize value to bonus. A method tSal should calculate and display the total salary. The

class test should test calculation of total salary done in these two classes in its Main function.

A. using System;

Class Dept1

{

protected int sal;

Public void eSal()

{

sal =5000;

}

}

Page 50: c# QBANK SOL (1)

Question Bank Solution for C#

50 | P a g e

Class Dept2:Dept1

{

int bonus;

int ts;

Public Dept2 ()

{

bonus = 500;

}

Public tSal ()

{

ts= sal + bonus;

MessageBox.Show (ts.ToString ());

}

}

Class Test

{

Public static void Main()

{

Dept2 obj=new Dept2 ();

obj.eSal ();

obj.tSal ();

}

Q.48 An educational institution wishes to maintain a database of its employees. The database is divided

into a number of classes whose heirachial relationships are shown below. The figure also shows

the minimum information required by each class. Specify all the classes and define methods to

create the database and retrieve individual information as and when required.

staff

code

Page 51: c# QBANK SOL (1)

Question Bank Solution for C#

51 | P a g e

A. Class staff

{

int code;

staff (int a) {code= a;}

Public void display ()

{

Console.Writeline (―Staff Code:- {0}‖,code);

}

}

Class teacher: staff

{

String sub;

int pub;

teacher (String a, int p, int c): base ( c )

teacher

subject,publicati

on typist

officer

grade

regular

speed

casual

Page 52: c# QBANK SOL (1)

Question Bank Solution for C#

52 | P a g e

{

sub =a; pub= p;

}

Public void display ()

{

base.display ();

Console.Writeline (―Subject:- ‖+sub);

Console.WriteLine (―Publication:- ‖,pub);

}

}

Class typist: staff

{

int speed;

Public typist (int p, int c): base (c)

{ speed = p; }

Public void display ()

{

base.display ();

Console.WriteLine (―Speed:- ‖, speed);

}

}

Class officer: staff

{

string grade;

Public officer (string g, int c)

{ grade= g; }

Page 53: c# QBANK SOL (1)

Question Bank Solution for C#

53 | P a g e

Public void display ()

{

base.display ();

Console.Writeline (―Grade of the officer is {0}‖,grade);

}

}

Class regular: typist

{

regular (int i): base (i) {}

Public void display()

{ base.display (); }

}

Class casual: typist

{

int dwages;

casual (int dw, int i): base (i)

{ dwages =dw; }

Public void display ()

{

base.display ();

Console.WriteLine (―Daily wages is {0}‖, dwages);

}

}

Class Program

{

Public static void Main ()

Page 54: c# QBANK SOL (1)

Question Bank Solution for C#

54 | P a g e

{

teacher t= new teacher (―Economics‖, 1200, HO2);

regular r= new regular (60);

officer o= new officer (―A‖, FOA);

casual c= new casual (5000, 60);

t.display ();

r.display ();

o.display ();

c.display ();

}

}

Q.49 Create a class Vehicle that has a data member vehiclepower. Define a property for power and a

method IncreaseVelocity that takes a parameter vehicle power value and displays message.

Create another class Automobile that is derived from vehicle and it overrides the

IncreaseVelocity method wherein if power is more than 120 then it is reduced to 120.Add a

method Color that takes color as argument and displays it. Create a class BMW tat is derived

from Automobile and overrides the method Color.

A. using System;

Class PolymorphismDemo

{

Static void Main ()

{

Automobile a=new Automobile ();

a.PowerSource=‖‖100 H.P;

a.IncreaseVelocity (60);

BMW car= new BMW ();

car.Color (―Black‖);

Console.WriteLine (―\n Press enter to exit :--‖);

Console.ReadLine ();

}

}

Class Vehicle

{

String Vehiclepower= ―‖;

Public string PowerSource

{

set

Page 55: c# QBANK SOL (1)

Question Bank Solution for C#

55 | P a g e

{

VehiclePower=value;

Console.WriteLine (―Power of engine is set to {0}‖, value.ToString());

}

get

{

return VehiclePower;

}

}

Public virtual IncreaseVelocity (int i)

{

Console.WriteLine (―The speed increases to ―+i.ToString()+‖m.h.p‖);

}

}

Class Automobile: Vehicle

{

Public override void IncreaseVelocity (int i)

{

If (i>120)

{

i=120;

}

Console.Writeline (―Press the accelerator to increase its speed to {0}‖,

i.ToString () +‖m.p.h‖);

}

Public virtual void Color (string col)

{

col=‖Blue‖;

Console.WriteLine(―The color of BMW is {0}‖,col);

}

}

Class BMW: Automobile

{

public override void Color(string col)

{

col=‖Navy‖;

Console.WriteLine(―The color of BMW is {0}‖,col);

}

}

Q.50 Create an abstract class Dimension_Shape that contains the following:

i. a protected member colorvalue

ii. a parameterized constructor

iii. a method getcolor that reads the color

iv. an abstract method getareaof_shape

Create a class ShapeCircle derived from Dimension_Shape that adds another private member

radius, a constructor and overrides method getareaof_shape that returns the area of circle. Create

class ShapeRect alse derived from Dimension_Shape having 2 members length and width of

Page 56: c# QBANK SOL (1)

Question Bank Solution for C#

56 | P a g e

rectangle, a constructor to assign values to length and width and override getareaof_shape to find

area of rectangle. Create another class ShapeSquare that has a member length of side of square, a

constructor and override method getareaof_shape to find area of square. Demonstrate the areas of

various figures.

A. using System;

Public abstract class Dimenson_Shape

{

Protected string colorvalue;

Public Dimension_Shape (string color)

{

this.colorvalue=color;

}

Public string getcolor ()

{

return colorvalue;

}

Public abstract double getareaof_shape ();

}

Class ShapeCircle: Dimension_Shape

{

Private double radius;

Public ShapeCircle (string colorvalue, double radius): base (colorvalue)

{

this.radius=radius;

}

Public override double getareaof_shape ()

{

return Math.PI*radius*radius;

}

}

Public ShapeRect: Dimension_Shape

{

Private double length;

Private double width;

Public ShapeRect (string colorvalue, double length, double width): base (colorvalue)

{

this.length=length;

this.width=width;

}

Public override double getareaof_shape ()

{

return length*width;

}

}

Public Shape Square: Dimension_Shape

{

Private double side;

Public ShapeSquare (string colorvalue, double length): base (colorvale)

{

Page 57: c# QBANK SOL (1)

Question Bank Solution for C#

57 | P a g e

this.side=length;

}

Public override double getareaof_shape ()

{

return side*side;

}

}

Class AreaandColor

{

Public static void Main ()

{

Dimension_Shape circle= new ShapeCircle (―Green‖, 6);

Dimension_Shape rect= new ShapeRect (―Maroon‖, 6, 8);

Dimension_Shape square= new ShapeSquare (―Black‖, 15);

Console.WriteLine (―Circle is of {0} Color and its area is {1}‖,

circle.getcolor (), circle.getareaof_shape ());

Console.WriteLine (―Recangle is of {0} Color and its area is {1}‖,

rect.getcolor (), rect.getareaof_shape ());

Console.WriteLine (―Square is of {0} Color and its area is {1}‖,

square.getcolor (), square.getareaof_shape ());

}

}

Q.51 Create a class Person with three data members: Age, Name, Gender. Derive a class called

Employee from Person that adds a data member Code to store the employee code. Derive another

class Specialist from Employee. Add a method to each derived class to display information about

the entity. Write a Driver program to generate array of three ordinary employees and another

array of 3 specialists and display information of specialist as also by calling method inherited

from employees.

A. using System;

class Person

{

public int age;

public string name;

public string gender;

public Person(){}

public Person(int a,string n,string g)

{

age=a;

name=n;

gender=g;

}

}

class employee:Person

{

Page 58: c# QBANK SOL (1)

Question Bank Solution for C#

58 | P a g e

int code;

public employee(){}

public employee(int a,string n,string g,int c):base(a,n,g)

{ code = c; }

public void display()

{

Console.WriteLine("age:-"+age+" name:-"+name+" gender:-"+gender);

}

}

class specialist:employee

{

public void display()

{

base.display();

Console.WriteLine("this is specialist class display");

}

}

class Test

{

public static void Main()

{

//employee i=new employee ();

employee []e=new employee[3];

e[0]=new employee(20,"shalini","female",101);

e [1]=new employee(20,"nirali","female",102);

e [2]=new employee(20,"rita","female",103);

foreach(employee i in e)

i.display ();

//specialist []s=new specialist[3];

//foreach(specialist i in s)

//i.display ();

}

}

Q.52 Create an application where the features: color, computer name, price and processor of a product

HPComputer are retrieved and displayed using different methods in a single Interface named

HPSystem. There is a class ComputerList that implements the interface but defines body for only

two characteristics—Computer name and Color. Another class ShowHPComputerDetails inherits

ComputerList has 2 data members for feature and price and implements those two methods. The

class ShowComputerFeatures contains the Main which displays various details of different

computers.

A. using System;

interface HPSystem

Page 59: c# QBANK SOL (1)

Question Bank Solution for C#

59 | P a g e

{

void ListComputer ();

void ShowComputerColor (string str);

void ShowComputerFeature (string feature);

void ShowComputerPrice (double price);

}

Class ComputerList: HPSystem

{

string color;

string name;

public void ListComputer()

{

name=‖1. HP Pavilion‖;

name=‖\n2. HP Compaq DC5673‖;

name=‖\n3. HP Compaq DC8756‖;

Console.WriteLine(―Computer names are:- ‖,name);

}

public void ShowComputerColor(string color)

{

this.color=color;

Console.WriteLine(―The color of the systems are: ‖,color);

}

public void ShowComputerFeature(){}

public void ShowComputerprice(){}

}

Class ShowHPComputerDetails: ComputerList

{

string feature;

string price;

public void ShowComputerFeature(string feature)

{

this.feature=feature;

Console.WriteLine(―The features of the systems are: ‖, feature);

}

public void ShowComputerPrice(string price)

{

this.price = price;

Console.WriteLine (―The prices of the systems are: ‖, price);

}

}

Class ShowComputerFeatures

{

public static void Main()

{

ShowHPComputerDetails s=new ShowHPComputerDetails ();

s.ListComputer ();

s.ShowComputerColor (―Steel Grey‖);

s.ShowComputerColor (―Black‖);

s.ShowComputerColor (―Steel Blue‖);

s.ShowComputerFeature (―Pentium PC Dual Core 2‖);

Page 60: c# QBANK SOL (1)

Question Bank Solution for C#

60 | P a g e

s.ShowComputerFeature (―Pentium PIV Core 2‖);

s.ShowComputerFeature (―Pentium PV Dual Core‖);

s.ShowComputerprice (―24000‖);

s.ShowComputerprice (―25090‖);

s.ShowComputerprice (―45000‖);

}

}

Q.53 Create abstract class ABS that shows the location on a console having two data members top, left

and a show method to display them. A class Class1 derives ABS and adds a new data member

contents that describes the location. Show the new member to the user. Another class Class2 also

derives ABS and simply shows the position on the console. The Main should create an array of 3

locations and show them to the user.2 objects of class1 and one as object of class2 should be the

elements of the array.

A. using System;

Class Program

{

Static void Main ()

{

ABS [] a=new ABS [3];

a [0]=new Class1(1,2,‖first value in array‖);

a [1]=new Class1(3,4,‖second value in array‖);

a [2]=new Class2(5,6);

For (int i=0; i<3; i++)

a [i].Show();

}

}

Public Abstract Class ABS

{

protected int top;

protected int left;

public ABS(int top, int left)

{

this.top=top;

this.left=left;

}

public abstract void Show()

}

public class Class1:ABS

{

private string class1values;

public class1(int top, int left, string contents):base(top, left)

{

class1values=contents;

}

public override void Show()

{

Page 61: c# QBANK SOL (1)

Question Bank Solution for C#

61 | P a g e

Console.WriteLine(―This overrides the show of abstract class

ABS:{0},class1values‖);

}

}

public class Class2:ABS

{

public Class2(int top, int left):base(top, left) { }

public override void Show()

{

Console.WriteLine(―overriding again the show method in class2‖,top,

left);

}

}

INTERFACES:

Q.54 Create an interface Area that are implemented by two classes Square and Circle that compute

their areas using the method Compute in the Interface Area. The Main class shows the

implementation of areas of any square and circle if Side of square is 12.5 and radius of circle is

15.27. (Area of square= (side*side) and area of circle=3.14*radius*radius)

A. using System;

Interface Area

{

double Compute (double x);

}

Class Square: Area

{

Public double Compute (double x)

{

Return(x*x);

}

}

Class Circle: Area

{

Public double Compute (double x)

{

Return (Math.PI*x*x);

}

}

Class InterfaceTest

{

Public static void Main ()

{

Square sq=new Square ();

Circle c=new Circle ();

Area asq;

asq =sq As Area;//casting

Page 62: c# QBANK SOL (1)

Question Bank Solution for C#

62 | P a g e

Console.WriteLine(―Area of square=‖, asq.Compute (12.5));

Area ac;

ac =c As Area;//casting

Console.WriteLine(―Area of circle=‖, ac.Compute (15.27));

}

}

Q.55 Create an application where the features: color, computer name, price and processor of a product

HPComputer are retrieved and displayed using different methods in a single Interface named

HPSystem. There is a class ComputerList that implements the interface but defines body for only

two characteristics—Computer name and Color. Another class ShowHPComputerDetails inherits

ComputerList has 2 data members for feature and price and implements those two methods. The

class ShowComputerFeatures contains the Main which displays various details of different

computers.

A. using System;

interface HPSystem

{

void ListComputer ();

void ShowComputerColor (string str);

void ShowComputerFeature (string feature);

void ShowComputerPrice (double price);

}

Class ComputerList: HPSystem

{

string color;

string name;

public void ListComputer()

{

name=‖1. HP Pavilion‖;

name=‖\n2. HP Compaq DC5673‖;

name=‖\n3. HP Compaq DC8756‖;

Console.WriteLine(―Computer names are:- ‖,name);

}

public void ShowComputerColor(string color)

{

this.color=color;

Console.WriteLine(―The color of the systems are: ‖,color);

}

public void ShowComputerFeature(){}

public void ShowComputerprice(){}

}

Class ShowHPComputerDetails: ComputerList

{

string feature;

string price;

public void ShowComputerFeature(string feature)

{

Page 63: c# QBANK SOL (1)

Question Bank Solution for C#

63 | P a g e

this.feature=feature;

Console.WriteLine(―The features of the systems are: ‖, feature);

}

public void ShowComputerPrice(string price)

{

this.price = price;

Console.WriteLine (―The prices of the systems are: ‖, price);

}

}

Class ShowComputerFeatures

{

public static void Main()

{

ShowHPComputerDetails s=new ShowHPComputerDetails ();

s.ListComputer ();

s.ShowComputerColor (―Steel Grey‖);

s.ShowComputerColor (―Black‖);

s.ShowComputerColor (―Steel Blue‖);

s.ShowComputerFeature (―Pentium PC Dual Core 2‖);

s.ShowComputerFeature (―Pentium PIV Core 2‖);

s.ShowComputerFeature (―Pentium PV Dual Core‖);

s.ShowComputerprice (―24000‖);

s.ShowComputerprice (―25090‖);

s.ShowComputerprice (―45000‖);

}

}

Q.56 Create an interface Area that are implemented by two classes Square and Circle that compute

their areas using the method Compute in the Interface Area. The Main class shows the

implementation of areas of any square and circle if Side of square is 12.5 and radius of circle is

15.27. (Area of square= (side*side) and area of circle=3.14*radius*radius)

A. using System;

Interface Area

{

double Compute (double x);

}

Class Square: Area

{

Public double Compute (double x)

{

Return(x*x);

}

}

Class Circle: Area

{

Public double Compute (double x)

{

Return (Math.PI*x*x);

Page 64: c# QBANK SOL (1)

Question Bank Solution for C#

64 | P a g e

}

}

Class InterfaceTest

{

Public static void Main ()

{

Square sq=new Square ();

Circle c=new Circle ();

Area asq;

asq =sq As Area;//casting

Console.WriteLine(―Area of square=‖, asq.Compute (12.5));

Area ac;

ac =c As Area;//casting

Console.WriteLine(―Area of circle=‖, ac.Compute (15.27));

}

}

Q.57 Create a class ExplicitInterface_Implementation that contains 2 interfaces: readFile and writeFile.

readFile has methods Read and Write. writeFile has 2 methods View and Read. A class

Document implements both interfaces. The methods should simply display any message. Class

ExplicitInterface_Implementation contains a createDoc method that checks if the interface objects

are null and then reads data. The method show also views the data. The main class shows the

document so created.

A. using System;

Class ExplicitInterface_Implementation

{

Interface readFile

{

Void Read ();

Void Write ();

}

Interface writeFile

{

Void View ();

Void Read ();

}

Page 65: c# QBANK SOL (1)

Question Bank Solution for C#

65 | P a g e

Public class Document: readFile, writeFile

{

Public Document (String doc)

{

Console.WriteLine (―Creating a document with : {0}‖,doc);

}

//Implicit implementation

Public virtual void Read ()

{

Console.WriteLine (―Reading from read method of interface readFile‖);

}

Public virtual void Write ()

{

Console.WriteLine (―Writing from Write method of interface readFile‖);

}

//explicit implementation

Void writeFile.Read ()

{

Console.WriteLine (―Reading from read method of interface writeFile‖);

}

Public void View ()

{

Console.WriteLine (―Viewing from view method of interface writeFile‖);

}

Public void createDoc ()

Page 66: c# QBANK SOL (1)

Question Bank Solution for C#

66 | P a g e

{

//creating a document object

Document d1=new Document (―This is a new document‖);

readFile r1=d1 As readFile;

If (r1! = null)

r1.Read ();

//casting to writeFile interface

writeFile w1=d1 As writeFile;

If (w1! = null)

w1.Read ();

d1.Read ();

d1.View ();

}

Public static void Main ()

{

ExplicitInterface_Implementation e=new ExplicitInterface_Implementation();

e.createDoc();

}

}

Q.58 Write a C# program that has two interfaces named: IEnglishDimensions, IMetricDimensions.

Both having methods floatLength and floatWidth. The class Box has two data members:

lengthInches and widthInches. Class Box implements the two interfaces (explicit implementation

is to be done). (Hint: English representation of length and width are same as entered by user.

Metric representation is length in inches *2.54 and width in inches *2.54) Display the length and

width in both representation types.

A. using System;

// Declare the English units interface:

interface IEnglishDimensions

{

float Length();

Page 67: c# QBANK SOL (1)

Question Bank Solution for C#

67 | P a g e

float Width();

}

// Declare the metric units interface:

interface IMetricDimensions

{

float Length();

float Width();

}

// Declare the "Box" class that implements the two interfaces:

// IEnglishDimensions and IMetricDimensions:

class Box : IEnglishDimensions, IMetricDimensions

{

float lengthInches;

float widthInches;

public Box(float length, float width)

{

lengthInches = length;

widthInches = width;

}

// Explicitly implement the members of IEnglishDimensions:

float IEnglishDimensions.Length()

{

return lengthInches;

}

float IEnglishDimensions.Width()

{

return widthInches;

}

// Explicitly implement the members of IMetricDimensions:

float IMetricDimensions.Length()

{

return lengthInches * 2.54f;

}

float IMetricDimensions.Width()

{

return widthInches * 2.54f;

}

public static void Main()

{

// Declare a class instance "myBox":

Box myBox = new Box(30.0f, 20.0f);

// Declare an instance of the English units interface:

IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;

Page 68: c# QBANK SOL (1)

Question Bank Solution for C#

68 | P a g e

// Declare an instance of the metric units interface:

IMetricDimensions mDimensions = (IMetricDimensions) myBox;

// Print dimensions in English units:

System.Console.WriteLine("Length(in): {0}", eDimensions.Length());

System.Console.WriteLine("Width (in): {0}", eDimensions.Width());

// Print dimensions in metric units:

System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());

System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());

}

}

Q.59 Create a class called ByTwos which generates a series of numbers each two greater than previous

one. There is ISeries interface containing three methods:

i. getNext ---returns next member in series

ii. reset ---resets the count

iii. setStart ---sets the starting value

Demonstrate the use of the interface ISeries in the class ByTwos.

A. using System;

// Define the interface

public interface ISeries

{

int getNext(); // return next number in series

void reset(); // restart

void setStart(int x); // set starting value

}

// Use ISeries to generate a sequence of even numbers.

class ByTwos : ISeries

{

int start;

int val;

public ByTwos()

{

start = 0;

val = 0;

}

public int getNext()

{

val += 2;

return val;

}

Page 69: c# QBANK SOL (1)

Question Bank Solution for C#

69 | P a g e

public void reset()

{

val = start;

}

public void setStart (int x)

{

start = x;

val = start;

}

}

class SeriesDemo

{

public static void Main()

{

ByTwos twoOb = new ByTwos ();

ISeries ob;

For (int i=0; i < 5; i++)

{

ob = twoOb;

Console.WriteLine ("Next ByTwos value is" +ob.getNext ());

}

}

}

Q.60 The class Computation implements two interfaces, Addition and Multiplication. It declares two

data members and defines the code for methods Add () and Mul ().Write a program to find the

addition and multiplication of 120 and 12.239.

A. using System;

Interface Addition

{

double Add();

}

Interface Multiplication

{

double Mul();

}

Class Computation: Addition, Multiplication

{

double x, y;

public Computation (double x, double y)

{

this.x=x;

this.y=y;

Page 70: c# QBANK SOL (1)

Question Bank Solution for C#

70 | P a g e

}

public double Add ()

{

return (x+y);

}

public double Mul ()

{

return (x*y) ;

}

}

Class InterfaceTest

{

public static void Main()

{

Computation c=new Computation (120, 12.239);

Addition add= (Addition) c; //casting

Console.WriteLine (‖Sum:-―, add. Add ());

Multiplication mult = (Multiplication) c; //casting

Console.WriteLine (‖Product:-―, mult. Mul ());

}

}

EXCEPTION HANDLING:

Q.61 Define an exception NotInRange. If the user enters a number other than the range 1 to 100 then

handle the error using the exception so created.

A. using System;

class NotInRange : Exception

{

public NotInRange(): base(){}

public NotInRange(string msg): base(msg){}

public NotInRange(string msg, Exception e): base(msg, e){}

}

class Test

{

public static void Main()

{

Page 71: c# QBANK SOL (1)

Question Bank Solution for C#

71 | P a g e

int x;

Console.Write("Enter Number ->");

x = int.Parse(Console.ReadLine());

try

{

if (!(x >= 1 && x <= 100))

throw new NotInRange();

}

catch (NotInRange e)

{

Console.WriteLine(e.Message);

}

Console.Read();

}

}

Q.62 Create two arrays containing values as below:

Array1---4, 8, 19, 25, 20, 180, 164

Array2---0, 5, 7, 3, 5, 2, 0

Divide the values of first array by the corresponding element in second array with exception

handling incorporated in it (a nested handling of exceptions).

A. using System;

class NestedExceptionDemo

{

public static void Main()

{

int [] numer = { 4, 8,19, 25, 20, 180, 164 };

int [] denom = { 0, 5, 7, 3, 5, 2, 0 };

For (int i=0; i < numer.Length; i++)

{

Try

{

Console.WriteLine (numer[i] + " / " +

Page 72: c# QBANK SOL (1)

Question Bank Solution for C#

72 | P a g e

Denom [i] + "is" +

numer [i]/denom [i]);

}

}

Catch (DivideByZeroException)

{

// catch the exception

Console.WriteLine ("Can't divide by Zero!");

}

catch (IndexOutOfRangeException)

{

// catch the exception

Console.WriteLine ("No matching element found.");

}

}

}

Q.63 Write a program to accept status from user and display a message related with status. If the user‘s

input does not match any of the messages of status then handle it by creating an exception called

NoMatchException. Status has values: Ready=1, offline, Waiting, TransmitOK, ReceiveOK,

Online.

A. using System;

enum status {Ready=1, Offline, Waiting, TransmitOk, ReceiveOk, Online};

using System;

class NoMatchException : Exception

{

public NoMatchException(): base(){}

public NoMatchException(string msg): base(msg){}

public NoMatchException(string msg, Exception e): base(msg, e){}

}

Class TestStatus

{

Public static void Main ()

{

int c=0;

Page 73: c# QBANK SOL (1)

Question Bank Solution for C#

73 | P a g e

Console.Write (―Enter the status:-----‖);

Try

{

c=int.Parse (Console.ReadLine());

If (c>6)

throw new NoMatchException();

Else

Console.WriteLine (―Status-----> ‖+status(c));

}

catch (NoMatchException e)

{

Console.WriteLine (e.Message);

}

Console.Read ();

}

}

Q.64 Define a method that would sort an array of integers. Incorporate exception handling mechanism

for ―index out of bounds‖ situations.

A. using System;

Class program

{

public void Sortedarray (int []num)

{

int n, i=0, j=0;

For (i=1; i< num.Length; i++)

{

For (j=1; j< num.Length; j++)

{

Page 74: c# QBANK SOL (1)

Question Bank Solution for C#

74 | P a g e

If (num [j-1]>num [j])

{

n=num [j-1];

num [j-1]=num [j];

num [j]=n;

}

}

}

Console.WriteLine (―Sorted List‖);

For (i=1; i<num.Length; i++)

Console.WriteLine (num[i]);

}

public static void Main()

{

int [] a = new int [10];

Console.WriteLine (―Enter 10 numbers‖);

Try

{

While (i< 10)

Console.ReadLine (num [i++]);

}

Catch (IndexOutOfRangeException e)

{

Console.WriteLine (―array can hold only hold 10 elements. You have

entered more than 10 values‖);

}

}

}

Page 75: c# QBANK SOL (1)

Question Bank Solution for C#

75 | P a g e

Q.65 Write a program that will read a name from the keyboard and display it on the screen. The

program should throw an exception when the length of the name is more than 15 characters.

Design your own exception mechanism.

A. using System;

class LengthException : Exception

{

public LengthException (): base(){}

public LengthException (string msg): base(msg){}

public LengthException (string msg, Exception e): base(msg, e){}

}

class Test

{

public static void Main()

{

string x;

Console.Write ("Enter a name ->");

x = Console.ReadLine ();

try

{

If (x.Length>15)

throw new LengthException ();

}

catch (LengthException e)

{

Console.WriteLine (e.Message);

}

Console.Read ();

Page 76: c# QBANK SOL (1)

Question Bank Solution for C#

76 | P a g e

}

}

DELEGATES AND EVENTS:

Q.66 Create a delegate DirectionDef and a class Direct that defines 4 methods:

i. East() to display ‗Direction is East‘

ii. West() to display ‗Direction is West‘

iii. North() to display ‗Direction is North‘

iv. South() to display ‗Direction is South‘

There is a method IdentifyDirection that creates objects to take any of the directions. Other

method that shows the message of directions. The class TestDirection should show

implementation of these methods.

A. using System;

public delegate void DirectionDef();

class Direct

{

DirectionDef [] t = new DirectionDef [3];

public static void East()

{

Console.WriteLine ("Direction is East");

}

public static void West()

{

Console.WriteLine ("Direction is West");

}

public static void North()

{

Console.WriteLine ("Direction is North");

}

Page 77: c# QBANK SOL (1)

Question Bank Solution for C#

77 | P a g e

public static void South()

{

Console.WriteLine ("Direction is South");

}

public void IdentifyDirection()

{

t[0] = new DirectionDef (Direct.East);

t[1] = new DirectionDef (Direct.West);

t[2] = new DirectionDef (Direct.North);

t[3] = new DirectionDef (Direct.South);

}

public void show(int i)

{ t[i].Invoke() ; }

}

class TestDirection

{

public static void Main()

{

Console.Write ("Enter Direction Code(0/1/2/3)->");

int i=int.Parse(Console.ReadLine());

Direct t1=new Direct ();

t1.IdentifyDirection ();

t1.show (i);

Console.Read ();

Page 78: c# QBANK SOL (1)

Question Bank Solution for C#

78 | P a g e

}

}

Q.67 Create a delegate strMod of string type. Create a class DelegateTest having three static methods:

i. ReplaceSpaces that replaces spaces by hyphens

ii. RemoveSpaces that removes spaces from string

iii. ReverseString that reverses a string

The Main method should implement the delegate.

A. using System;

delegate string StrMod(string str);

class DelegateTest

{

// Replaces spaces with hyphens.

static string replaceSpaces(string a)

{

Console.WriteLine("Replaces spaces with hyphens.");

return a.Replace(' ', '-');

}

// Remove spaces.

static string removeSpaces(string a)

{

string temp = "";

int i;

Console.WriteLine ("Removing spaces.");

For (i=0; i < a.Length; i++)

{

If (a [i] ! = ' ')

temp += a[i];

}

return temp;

}

// Reverse a string.

static string reverse(string a)

{

string temp = "";

int i, j;

Console.WriteLine ("Reversing string.");

For (j=0, i=a.Length-1; i >= 0; i--, j++)

temp += a[i];

return temp;

}

public static void Main()

{

// Construct a delegate.

Page 79: c# QBANK SOL (1)

Question Bank Solution for C#

79 | P a g e

StrMod strOp = new StrMod (replaceSpaces);

string str;

// Call methods through the delegate.

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

strOp = new StrMod(removeSpaces);

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

strOp = new StrMod(reverse);

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

}

}

Q.68 Solve the above program where the methods are instance methods.

A. using System;

delegate string StrMod(string str);

class DelegateTest

{

// Replaces spaces with hyphens.

static string replaceSpaces(string a)

{

Console.WriteLine("Replaces spaces with hyphens.");

return a.Replace(' ', '-');

}

// Remove spaces.

static string removeSpaces(string a)

{

string temp = "";

int i;

Console.WriteLine ("Removing spaces.");

For (i=0; i < a.Length; i++)

{

If (a [i] ! = ' ')

temp += a[i];

}

return temp;

}

// Reverse a string.

static string reverse(string a)

{

string temp = "";

int i, j;

Console.WriteLine ("Reversing string.");

Page 80: c# QBANK SOL (1)

Question Bank Solution for C#

80 | P a g e

For (j=0, i=a.Length-1; i >= 0; i--, j++)

temp += a[i];

return temp;

}

}

class DelegateTest

{

public static void Main()

{

StringOps so = new StringOps (); //create an instance

// Initialize a delegate.

StrMod strOp = so.replaceSpaces;

string str;

// Call methods through delegates.

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

strOp = so.removeSpaces;

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

strOp = so.reverse;

str = strOp("This is a test.");

Console.WriteLine("Resulting string: " + str);

}

}

Q.69 Create delegate, class and methods as in Q.33 and perform following operations in the main class:

i. Add hyphen and remove space

ii. Remove hyphen and add space

iii. Remove space and reverse the string

Display the resultant string.

A. using System;

delegate void StrMod(ref string str);

class MultiCastDemo

{

// Replaces spaces with hyphens.

static string replaceSpaces(string a)

{

Console.WriteLine("Replaces spaces with hyphens.");

return a.Replace(' ', '-');

}

// Remove spaces.

static string removeSpaces(string a)

{

Page 81: c# QBANK SOL (1)

Question Bank Solution for C#

81 | P a g e

string temp = "";

int i;

Console.WriteLine ("Removing spaces.");

For (i=0; i < a.Length; i++)

{

If (a [i] ! = ' ')

temp += a[i];

}

return temp;

}

// Reverse a string.

static string reverse(string a)

{

string temp = "";

int i, j;

Console.WriteLine ("Reversing string.");

For (j=0, i=a.Length-1; i >= 0; i--, j++)

temp += a[i];

return temp;

}

public static void Main()

{

// Construct delegates.

StrMod strOp;

StrMod replaceSp = replaceSpaces;

StrMod removeSp = removeSpaces;

StrMod reverseStr = reverse;

string str = "This is a test";

// Set up multicast.

strOp = replaceSp;

strOp += reverseStr;

// Call multicast.

strOp(ref str);

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

// Remove replace and add remove.

strOp -= replaceSp;

strOp += removeSp;

str = "This is a test"; // reset string

// Call multicast.

strOp(ref str);

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

Page 82: c# QBANK SOL (1)

Question Bank Solution for C#

82 | P a g e

// Remove space and add reverse.

strOp -= removeSp;

strOp += reverseStr;

str = "This is a test"; // reset string

// Call multicast.

strOp(ref str);

Console.WriteLine("Resulting string: " + str);

Console.WriteLine();

}

}

Q.70 Create a delegate ShowInterest with two double parameters to return a double. A class Interest

has four methods:

i. To accept value of Principal from user and return it.

ii. To accept value of Interest Rate from user and return it.

iii. To accept value of Period(in years) from user and return it.

iv. A method CalculateInterest that calculates the Simple Interest accepting values and

returning the Interest.

A class CalculateLoan has a static method AddupAmount that adds the principal and loan amount

passes to the delegate object. Assign values to principal, rate, period and loan amount using

methods of Interest class. Display the calculated loan details in the Main method.

A. using system;

delegate double ShowInterest (double val1, double val2);

Class Interest

{

public double Principal()

{

Console.Write (―Enter the principal Rs.‖);

double p=double.Parse (Console.ReadLine ());

return p;

}

public double InterestRate ()

{

Console.Write (―Enter the InterestRate in (%)‖);

double r=double.Parse (Console.ReadLine ());

return r;

}

public double Time ()

{

Console.Write (―Enter the Time in (%)‖);

double t=double.Parse (Console.ReadLine ());

return t;

}

public double CalculateInterest (double p, double r, double t)

Page 83: c# QBANK SOL (1)

Question Bank Solution for C#

83 | P a g e

{

return p*(r/100)*t;

}

}

Class CalculateLoan

{

static int Main(string []a)

{

double p, r, t, amt;

double duration=0;

string durationname=null;

Interest i=new Interest ();

ShowInterest s= new showInterest (AddUpAmount);

Console.Writeline (―program to calculate Loan Amount in Simple

interest‖);

Console.WriteLine (― ‖);

p=i.Principal ();

r=i.InterestRate ();

t=i.Time ();

amt = i.CalculateInterest (p, r, t);

double Amount=s(p, amt);

durationname=‖years‖;

Console.WriteLine (―==================‖);

Console.WriteLine (―Calculate Loan‖);

Console.WriteLine (―-----------------------------‖);

Console.WriteLine (―Principal: {0}‖, p);

Console.WriteLine (―Interest: {1}‖, r);

Console.WriteLine (―Period: {2}‖, t, durationname);

Console.WriteLine (―-----------------------------‖);

Console.WriteLine (―Interest to be paid on Loan Rs. :{0}‖, amt);

Console.WriteLine (―Total amount to pay after‖+t+‖years Rs: {0}‖,

Amount);

Console.WriteLine (―==================‖);

return 0;

}

public static double AddUpAmount (double val1, double val2)

{

return val1+val2;

}

}

OPERATOR OVELOADING:

Q.71 Create a class Float that contains one float data member over all four basic arithmetic operators

that can be applied to object of float. Use overloaded ToString method to provide output in

required format.

A. using System;

Page 84: c# QBANK SOL (1)

Question Bank Solution for C#

84 | P a g e

class test

{

float num;

public test()

{

num = 3F;

}

public test(float x)

{

num=x;

}

public static test operator +(test a,test b)

{

test c=new test();

c.num=a.num+b.num;

return(c);

}

public static test operator -(test a,test b)

{

test c=new test();

c.num=a.num-b.num;

return(c);

}

public static test operator *(test a,test b)

{

test c=new test();

Page 85: c# QBANK SOL (1)

Question Bank Solution for C#

85 | P a g e

c.num=a.num*b.num;

return(c);

}

public static test operator /(test a,test b)

{

test c=new test();

c.num=a.num/b.num;

return(c);

}

public void show()

{

string s = num.ToString();

Console.WriteLine("Number is :---- " + s);

}

}

class testdemo

{

public static void Main()

{

test ex1 = new test(4f);

test ex2 = new test(5f);

ex1.show();

ex2.show();

test ex3 = new test();

ex3 = ex1 + ex2;

Page 86: c# QBANK SOL (1)

Question Bank Solution for C#

86 | P a g e

ex3.show();

test ex4 = new test();

ex4 = ex1 - ex2;

ex4.show();

test ex5 = new test();

ex5 = ex1 * ex2;

ex5.show();

ex1 = ex1 / ex2;

ex1.show ();

Console.Read();

}

}

Q.72 Create a class Matrix (m x n). Define matrix operations (+,-,*) of matrix objects.

A. using System;

class Matrix

{

public int m,n;

public int[,] arr;

public Matrix()

{}

public Matrix(int r,int c)

{

m=r;n=c;

arr = new int[m,n];

}

Page 87: c# QBANK SOL (1)

Question Bank Solution for C#

87 | P a g e

public void ReadMatrix()

{

//arr = new int[m,n];

Console.WriteLine("Enter the values of the Matrix:");

for(int i=0;i<m;i++)

{

for(int j=0;j<n;j++)

{

arr[i,j]=int.Parse(Console.ReadLine());

}

}

}

public static Matrix operator +(Matrix m1,Matrix m2)

{

Matrix temp=new Matrix();

if(m1.m==m2.m && m1.n==m2.n)

{

//will the line below execute??

temp=new Matrix(m1.m,m1.n);

for(int i=0;i<temp.m;i++)

{

for(int j=0;j<temp.n;j++)

{

temp.arr[i,j]=m1.arr[i,j]+m2.arr[i,j];

Page 88: c# QBANK SOL (1)

Question Bank Solution for C#

88 | P a g e

}

}

}

else

{

Console.WriteLine("Matrix Size not Suitable");

Environment.Exit(-1);

}

return temp;

}

public static Matrix operator -(Matrix m1,Matrix m2)

{

Matrix temp=new Matrix();

if(m1.m==m2.m && m1.n==m2.n)

{

//will the line below execute??

temp=new Matrix(m1.m,m1.n);

for(int i=0;i<temp.m;i++)

{

for(int j=0;j<temp.n;j++)

{

temp.arr[i,j]=m1.arr[i,j]-m2.arr[i,j];

}

}

}

Page 89: c# QBANK SOL (1)

Question Bank Solution for C#

89 | P a g e

else

{

Console.WriteLine("Matrix Size not Suitable");

Environment.Exit(-1);

}

return temp;

}

public static Matrix operator *(Matrix m1,Matrix m2)

{

Matrix temp=new Matrix();

if(m1.n==m2.m)

{

//will the below constructor execute??

temp=new Matrix(m1.m,m2.n);

for(int i=0;i<temp.m;i++)

{

for(int j=0;j<temp.n;j++)

{

temp.arr[i,j]=0;

for(int k=0;k<temp.m;k++)

temp.arr[i,j]=temp.arr[i,j]+ m1.arr[i,k] * m2.arr[k,j];

}

}

}

else

{

Page 90: c# QBANK SOL (1)

Question Bank Solution for C#

90 | P a g e

Console.WriteLine("Matrix Size not Suitable");

Environment.Exit(-1);

}

return temp;

}

public void displayMatrix()

{

Console.WriteLine("The Resultant Matrix is:");

for(int i=0;i<m;i++)

{

for(int j=0;j<n;j++)

{

Console.Write("\t"+arr[i,j]);

}

Console.WriteLine();

}

}

}

class TestMatrix

{

public static void Main()

{

Matrix m1=new Matrix(2,3);

Page 91: c# QBANK SOL (1)

Question Bank Solution for C#

91 | P a g e

Matrix m2=new Matrix(2,3);

Matrix m4=new Matrix(3,3);

Matrix m3;

m1.ReadMatrix();

m2.ReadMatrix();

m4.ReadMatrix();

//Addition

m3=m1+m2;

m3.displayMatrix();

//Subtraction

m3=m1-m2;

m3.displayMatrix();

//Multiplication

m3=m1*m4;

m3.displayMatrix();

Console.Read();

}

}

Q.73 Write a program to overload Binary + and -. Create class ThreeD and make three objects of the

class. Two of them having three arguments and one with single argument. Then perform the

following:

i. Show all the three objects

ii. Add first two objects into third and show third object.

iii. Add all three into third and show third object.

iv. Subtract first object from third object and store in third object. Display the third object.

A. using System;

// A three-dimensional coordinate class.

class ThreeD

{

int x, y, z; // 3-D coordinates

public ThreeD() { x = y = z = 0; }

Page 92: c# QBANK SOL (1)

Question Bank Solution for C#

92 | P a g e

public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }

// Overload binary +.

public static ThreeD operator +(ThreeD op1, ThreeD op2)

{

ThreeD result = new ThreeD();

/* This adds together the coordinates of the two points

and returns the result. */

result.x = op1.x + op2.x; //integer additions

result.y = op1.y + op2.y; //+ retains its original

result.z = op1.z + op2.z; // meaning relative to them.

return result;

}

// Overload binary -.

public static ThreeD operator -(ThreeD op1, ThreeD op2)

{

ThreeD result = new ThreeD();

/* Notice the order of the operands. op1 is the left

operand and op2 is the right. */

result.x = op1.x - op2.x; //integer subtractions

result.y = op1.y - op2.y;

result.z = op1.z - op2.z;

return result;

}

// Show X, Y, Z coordinates.

public void show()

{

Console.WriteLine(x + ", " + y + ", " + z);

}

}

class ThreeDDemo

{

public static void Main()

{

ThreeD a = new ThreeD (1, 2, 3);

ThreeD b = new ThreeD (10, 10, 10);

ThreeD c = new ThreeD ();

Console.Write ("Here is a: ");

a.show ();

Console.WriteLine ();

Console.Write ("Here is b: ");

b.show ();

Console.WriteLine ();

c = a + b; // add a and b together

Console.Write ("Result of a + b: ");

c.show ();

Console.WriteLine ();

Page 93: c# QBANK SOL (1)

Question Bank Solution for C#

93 | P a g e

c = a + b + c; // add a, b and c together

Console.Write ("Result of a + b + c: ");

c.show ();

Console.WriteLine ();

c = c - a; // subtract a

Console.Write ("Result of c - a: ");

c.show ();

Console.WriteLine ();

}

}

Q.74 Demonstrate operator overloading to accomplish the following: Overload the operator + for:-

i. Object + Object

ii. Object + Int

iii. Int + Object

A. using System;

// A three-dimensional coordinate class.

class ThreeD

{

int x, y, z; // 3-D coordinates

public ThreeD() { x = y = z = 0; }

public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }

// Overload binary + for object + object.

public static ThreeD operator +(ThreeD op1, ThreeD op2)

{

ThreeD result = new ThreeD();

/* This adds together the coordinates of the two points

and returns the result. */

result.x = op1.x + op2.x;

result.y = op1.y + op2.y;

result.z = op1.z + op2.z;

return result;

}

// Overload binary + for object + int.

public static ThreeD operator +(ThreeD op1, int op2)

{

ThreeD result = new ThreeD();

result.x = op1.x + op2;

result.y = op1.y + op2;

result.z = op1.z + op2;

return result;

}

Page 94: c# QBANK SOL (1)

Question Bank Solution for C#

94 | P a g e

// Overload binary + for int + object.

public static ThreeD operator +(int op1, ThreeD op2)

{

ThreeD result = new ThreeD();

result.x = op2.x + op1;

result.y = op2.y + op1;

result.z = op2.z + op1;

return result;

}

// Show X, Y, Z coordinates.

public void show()

{

Console.WriteLine (x + ", " + y + ", " + z);

}

}

class ThreeDDemo

{

public static void Main()

{

ThreeD a = new ThreeD (1, 2, 3);

ThreeD b = new ThreeD (10, 10, 10);

ThreeD c = new ThreeD ();

Console.Write ("Here is a: ");

a.show ();

Console.WriteLine ();

Console.Write ("Here is b: ");

b.show ();

Console.WriteLine ();

c = a + b; // object + object

Console.Write ("Result of a + b: ");

c.show ();

Console.WriteLine();

c = b + 10; // object + int

Console.Write ("Result of b + 10: ");

c.show();

Console.WriteLine ();

c = 15 + b; // int + object

Console.Write ("Result of 15 + b: ");

c.show ();

}

}

Page 95: c# QBANK SOL (1)

Question Bank Solution for C#

95 | P a g e

Q.75 Overload the < and > operators. There is a class ThreeD with three data members. Implement

overloading such that one object is less than other only if all of its components are less then

corresponding coordinates of other object. Similarly for being greater also follow same rule.

A. using System;

// A three-dimensional coordinate class.

class ThreeD

{

int x, y, z; // 3-D coordinates

public ThreeD() { x = y = z = 0; }

public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }

// Overload <.

public static bool operator <(ThreeD op1, ThreeD op2)

{

if((op1.x < op2.x)&&(op1.y < op2.y)&&(op1.z < op2.z))

return true;

else

return false;

}

// Overload >.

public static bool operator >(ThreeD op1, ThreeD op2)

{

if((op1.x > op2.x)&&(op1.y > op2.y)&&(op1.z > op2.z))

return true;

else

return false;

}

// Show X, Y, Z coordinates.

public void show()

{

Console.WriteLine(x + ", " + y + ", " + z);

}

}

class ThreeDDemo

{

public static void Main()

{

ThreeD a = new ThreeD(5, 6, 7);

ThreeD b = new ThreeD(10, 10, 10);

ThreeD c = new ThreeD(1, 2, 3);

Console.Write("Here is a: ");

a.show();

Console.Write("Here is b: ");

b.show();

Console.Write("Here is c: ");

Page 96: c# QBANK SOL (1)

Question Bank Solution for C#

96 | P a g e

c.show();

Console.WriteLine();

if(a > c) Console.WriteLine("a > c is true");

if(a < c) Console.WriteLine("a < c is true");

if(a > b) Console.WriteLine("a > b is true");

if(a < b) Console.WriteLine("a < b is true");

}

}

Q.76 Create a class Mystring which has a show method to display string. Overload operator :

i. + to add two string objects

ii. == to check if two strings are equal

iii. – operator to check if string is empty

A. using System;

class MyString

{

String str;

public MyString(){ str = ""; }

public MyString(String s){ str = s; }

public void Show()

{

Console.WriteLine("String Is:" + str);

}

public static MyString operator +(MyString ob1, MyString ob2)

{

MyString ob3 = new MyString();

ob3.str = ob1.str + ob2.str;

return ob3;

}

public static bool operator ==(MyString ob1, MyString ob2)

{

if (ob1.str==ob2.str)

return true;

else

return false;

}

public static bool operator !=(MyString ob1, MyString ob2)

{

if (ob1.str!=ob2.str)

return true;

else

return false;

}

public static bool operator -(MyString ob1)

Page 97: c# QBANK SOL (1)

Question Bank Solution for C#

97 | P a g e

{

if (ob1.str=="")

return true;

else

return false;

}

}

class Abc

{

public static void Main()

{

MyString m1 = new MyString();

MyString m2 = new MyString("Welcome");

MyString m3 = new MyString("Everyone");

MyString m4 = new MyString();

MyString m5 = new MyString();

m1.Show();

m2.Show();

m3.Show();

m4 = m2 + m3;

m4.Show();

if(-m1)

Console.WriteLine("string is empty");

else

Console.WriteLine("string is not empty");

m1.Show();

Console.WriteLine(m1==m5);

Console.WriteLine(m1==m2);

Console.Read();

}

}

Q.77 Create a class Dated that has three integer data members: day, month, year .A method that sets

values to the members entered by user as command line arguments. A method to display these

values in the format: 12/5/1990.Overload operator ++ to increments the date by one. Display the

date in the main method in class TestDate.

A. using System;

class Dated

{

int day;

int mon;

int year;

public void Set()

Page 98: c# QBANK SOL (1)

Question Bank Solution for C#

98 | P a g e

{

day=int.Parse(Console.ReadLine());

mon=int.Parse(Console.ReadLine());

year=int.Parse(Console.ReadLine());

}

public void Display()

{

Console.WriteLine("Date is :{0}/{1}/{2}",day,mon,year);

}

public static Dated operator ++(Dated d1)

{

if (d1.day<=30)

{

d1.day++;

}

else if(d1.day>=30)

{

d1.day=0;

d1.mon++;

d1.day++;

}

else

Console.WriteLine("Hello");

return(d1);

}

}

class TestDate

{

public static void Main()

{

Dated d1=new Dated();

d1.Set();

d1.Display();

d1++;

d1.Display();

}

}

Q.78 Overload plus (+) operator. A static method Fraction takes two integer parameters and returns a

fraction output and displays the output as string type (use ToString method).

Page 99: c# QBANK SOL (1)

Question Bank Solution for C#

99 | P a g e

A. using System;

Class Calculate

{

public void calc ()

{

Fraction f1=new Fraction (24,224);

Console.WriteLine (―Fraction 1 is {0}‖, f1.ToString ());

Fraction f2=new Fraction (34,234);

Console.WriteLine (―Fraction 1 is {0}‖, f1.ToString ());

Fraction sum= f1+ f2;

Console.WriteLine (―The sum of two fraction is: {0}‖, sum .ToString ());

}

Static void Main ()

{

Calculate ca=new Calculate();

}

}

Class Fraction

{

int numerator;

int denominator;

//create a fraction by passing in the numerator and denominator

Public Fraction(int numerator, int denominator)

{

this. numerator= numerator;

this. denominator= denominator;

}

//overload operator + takes two fractions and returns their sum

Public static Fraction operator + (Fraction f1, Fraction f2)

{

//fractions with shared denominator can be added

//by adding their numerators

If (f1.denominator= f2.denominator)

{

return new Fraction(f1.numerator+f2.numerator,f1.denominator);

}

int prod1=f1.numerator* f2.denominator;

int prod2= f2.numerator* f1.denominator;

return new Fraction(prod1+prod2, f1.denominator* f2.denominator);

}

//return string representation of the fraction

Public override string ToString()

{

String s=numerator.ToString ()+ ―/‖ +denominator.ToString ();

return s;

}

}

Page 100: c# QBANK SOL (1)

Question Bank Solution for C#

100 | P a g e

MANAGING CONSOLE I/O OPERATIONS:

Q.79 Write a program to accept a floating point number from user in the number format with a dollar

sign and then in a formatted decimal way of ###. ### (use string builder methods Append,

AppendFormat to display the details).

A. using System;

Class Program

{

Static void Main ()

{

StringBuider s=new StringBuilder ();

Console.Writeline (―This is an example of custom number format‖);

double val;

Console.Write (―Enter a number :-―);

val=double.Parse (Console.ReadLine ());

s.Append (―\nThis is formatted output‖);

s.AppendFormat (―{0; $#, ###0.00; ($#.###0.00) ; Zero}‖,val );

Console.WriteLine(s.ToString());

}

}

Q.80 Write a program which formats the number 1973458783 in ## + ## * #### - ##, breaks the first

number in 19 + 73 * 4587 – 83. The second number 2662.63 with a decimal will be rounded off

to the nearest decimal 2662.6, if #. # number format is passed. Similarly, if only # is passed, the

second number will be rounded off with no decimal displayed as 2663.

A. using System;

Class Program

{

Static void Main ()

{

double val1=1973458783;

Console.Writeline (―First number is:- ‖+ val1);

Console.Writeline (―To be formatted in ## + ## * ### - ##‖);

String val2=val1.ToString (―## + ## * ### - ##‖);

Console.WriteLine (―Formatted first number:-- {0}‖,val2);

double val3=2662.63;

Console.Writeline (―Second number is:- ‖+ val3);

Console.Writeline (―To be formatted in #.#‖);

String val2=val3.ToString (―Formatted second number is #. #‖);

Console.WriteLine (val2);

}

}