Professional Documents
Culture Documents
C# QBANK SOL
C# QBANK SOL
C# QBANK SOL
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)
{
Console.WriteLine ();
Return 0;
}
}
10 20 30 40
60 70 80 90
A. using System;
1| Page
Question Bank Solution for C#
Class ContinueBreak
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;
Console.Write (― ‖+n);
n=n+10;
Console.Writeline ();
2| Page
Question Bank Solution for C#
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
int cost=0;
Switch (s)
Case ―S‖:
cost =cost+10;
break;
Case ―M‖:
cost =cost+15;
break;
Case ―L‖:
cost =cost+30;
break;
Default:
break;
3| Page
Question Bank Solution for C#
If (cost! = 0)
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‖);
}
4| Page
Question Bank Solution for C#
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
double f, c;
Console.WriteLine("Fahrenheit\t Celsius");
c = (f - 32) / 1.8;
Console.WriteLine("{0:F2}\t{1:F2}",f , c);
Console.Read ();
A. Class Series
Do
s= s+ (i/j);
i=i+2;
5| Page
Question Bank Solution for C#
j++;
While (i<=21);
A. Class Series
s= s+ x;
n=n+s;
A. Class Series
6| Page
Question Bank Solution for C#
For(x=1; x<=10; x++)
n= n* x;
s=s+n;
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;
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.
7| Page
Question Bank Solution for C#
A. using System;
Class InterestCalculator
{
public static void Main()
{
Console.WriteLine (―----Interest Calculator----‖);
Console.WriteLine (―Calculate Simple (S)/Compound (C) Interest‖);
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;
8| Page
Question Bank Solution for C#
// 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);
}
}
}
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 ();
If (str3.EndsWith(―IDE‖)==True)
Console.WriteLine (―True‖);
Else
Console.WriteLine (―False‖);
9| Page
Question Bank Solution for C#
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
String str1=‖‖;
String str2=‖‖;
str1=Console.ReadLine ();
str2=Console.ReadLine ();
int cap=b1.EnsureCapacity(55);
Console.WriteLine (b1);
10 | P a g e
Question Bank Solution for C#
Console.Write (―String str2 inserted with: ‖);
Console.WriteLine (b2);
Console.WriteLine (b2);
Console.WriteLine (b2);
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
11 | P a g e
Question Bank Solution for C#
public void Show()
String str1=‖‖;
String str2=‖‖;
String str3=@‖C# 2005 is one of the core languages of .Net. It provides a custom
.Net platform for development of applications‖;
p.Display ();
12 | P a g e
Question Bank Solution for C#
}
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
Str1=Console.ReadLine ();
Str2=Console.ReadLine ();
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;
13 | P a g e
Question Bank Solution for C#
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
14 | P a g e
Question Bank Solution for C#
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();
15 | P a g e
Question Bank Solution for C#
Console.WriteLine (―Replacing first two elements in the arraylist with
prime numbers‖);
a [0]=31;
a [1]=37;
}
}
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
16 | P a g e
Question Bank Solution for C#
{
int i, j, k, m, n;
Console.Write ("\n\n");
If (i > j)
17 | P a g e
Question Bank Solution for C#
}
int t=x;
x=y;
y=t;
return;
456
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;
18 | P a g e
Question Bank Solution for C#
jagged[2][i] = i;
Console.WriteLine();
Console.WriteLine();
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];
nextdigit = 0;
numdigits = 0;
19 | P a g e
Question Bank Solution for C#
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;
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;
20 | P a g e
Question Bank Solution for C#
Class ArrayTest
Console.WriteLine(―Enter 10 numbers‖);
While (i<10)
Console.ReadLine(num[i++])
n=num [j-1];
num [j]=n;
Console.WriteLine(―Sorted List‖);
Console.WriteLine(num[i]);
21 | P a g e
Question Bank Solution for C#
}
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
for(i=0;i<3;i++)
For(j=o;j<3;j++)
X[i,j]=Console.ReadLine();
Console.WriteLine ();
22 | P a g e
Question Bank Solution for C#
fr = int.Parse(Console.ReadLine());
sr = int.Parse(Console.ReadLine());
x[fr, i] = x[sr,i];
x[sr, i] = temp;
Console.WriteLine();
Console.Read();
METHODS IN C#:
23 | P a g e
Question Bank Solution for C#
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 ());
24 | P a g e
Question Bank Solution for C#
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;
}
}
}
A. using System;
class RevStr
{
class RevStrDemo
{
public static void Main()
{
string s = "this is a test";
RevStr rsOb = new RevStr();
Console.WriteLine();
}
}
25 | P a g e
Question Bank Solution for C#
Q.30 Create a ChkNum class that contains 2 methods:
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 1;
}
}
class ParmDemo
{
public static void Main()
{
ChkNum ob = new ChkNum ();
int a, b;
26 | P a g e
Question Bank Solution for C#
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
27 | P a g e
Question Bank Solution for C#
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;
28 | P a g e
Question Bank Solution for C#
}
}
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
29 | P a g e
Question Bank Solution for C#
{
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;
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);
30 | P a g e
Question Bank Solution for C#
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:
A class StudentMenu shows the degree for which the student got admission along with his details
and also displays a message of format:-
A. using System;
Class Select
public Select
degree= Degree.Civil;
31 | P a g e
Question Bank Solution for C#
degree=Degree.Civil;
Class GetDetails
Select degree;
public GetDetails ()
degree=new Select();
int c=0;
Console.WriteLine(―1. Mechanical‖);
Console.WriteLine(―2. Electrical‖);
Console.WriteLine(―3. Electronics‖);
Console.WriteLine(―4. Aeronautics‖);
c=Console.ReadLine();
Switch(c)
case 1:
32 | P a g e
Question Bank Solution for C#
degree.degree= Degree.Mechanical; break;
case 2:
case 3:
case 4:
default:
name = Console.ReadLine();
Console.Write(―Enter address‖);
address = Console.ReadLine();
telephone = Console.ReadLine();
Console.Write(―Enter course‖);
course = Console.ReadLine();
fees = Console.ReadLine();
33 | P a g e
Question Bank Solution for C#
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:
34 | P a g e
Question Bank Solution for C#
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;
35 | P a g e
Question Bank Solution for C#
Employee salary;
}
Class ShowEmployeeDetails
{
Static void Main ()
{
string input=‖‖;
EmployeeDetails e=new EmployeeDetails ();
e.ShowAllDetails();
Console.WriteLine ();
36 | P a g e
Question Bank Solution for C#
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;
Class school
{
Public string schoolname;
Public string classname;
37 | P a g e
Question Bank Solution for C#
}
}
Public struct teachers
{
Public string tcode;
Public string 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 ();
38 | P a g e
Question Bank Solution for C#
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
class Test
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);
39 | P a g e
Question Bank Solution for C#
a.Add (languages.French);
foreach (int i in a)
Console.Read ();
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);
Q.40 Design a class to represent a bank account. Include the following members;
40 | P a g e
Question Bank Solution for C#
Data Members:
Methods:
A. Class Account
String name;
Double bal;
String acno;
String actype;
bal =bal+amt;
If (amt<= bal)
41 | P a g e
Question Bank Solution for C#
bal =bal-amt;
Else
Class program
a.Deposit (255.076);
a.Show ();
a.Withdraw (158.127);
a.Show ();
42 | P a g e
Question Bank Solution for C#
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
{
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.WriteLine();
}
}
Q.42 Create a class Building with three members: floors, area, occupants. Add two methods:
43 | P a g e
Question Bank Solution for C#
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
A. using System;
class Destruct
{
public int x;
public Destruct(int i) { x = i; }
44 | P a g e
Question Bank Solution for C#
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;
45 | P a g e
Question Bank Solution for C#
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 ();
Console.WriteLine ();
}
}
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
46 | P a g e
Question Bank Solution for C#
{
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();
47 | P a g e
Question Bank Solution for C#
{
minmks = m[i];
index = i+1;
}
}
Console.WriteLine(―You have scored minimum marks {0} in subject
{1}‖, minmks, index);
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];
48 | P a g e
Question Bank Solution for C#
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
sal =5000;
49 | P a g e
Question Bank Solution for C#
Class Dept2:Dept1
int bonus;
int ts;
Public Dept2 ()
bonus = 500;
Public tSal ()
Class Test
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 50 | P a g e
Question Bank Solution for C#
teacher officer
grade
subject,publicati typist
on
speed
regular casual
A. Class staff
int code;
String sub;
int pub;
51 | P a g e
Question Bank Solution for C#
{
base.display ();
int speed;
{ speed = p; }
base.display ();
string grade;
{ grade= g; }
52 | P a g e
Question Bank Solution for C#
Public void display ()
base.display ();
{ base.display (); }
int dwages;
{ dwages =dw; }
base.display ();
Class Program
53 | P a g e
Question Bank Solution for C#
{
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);
}
Class Vehicle
{
String Vehiclepower= ―‖;
Public string PowerSource
{
set
54 | P a g e
Question Bank Solution for C#
{
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:
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
55 | P a g e
Question Bank Solution for C#
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)
{
56 | P a g e
Question Bank Solution for C#
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
{
57 | P a g e
Question Bank Solution for C#
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
58 | P a g e
Question Bank Solution for C#
{
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‖);
59 | P a g e
Question Bank Solution for C#
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);
60 | P a g e
Question Bank Solution for C#
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
61 | P a g e
Question Bank Solution for C#
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)
{
62 | P a g e
Question Bank Solution for C#
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);
63 | P a g e
Question Bank Solution for C#
}
}
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
Interface writeFile
64 | P a g e
Question Bank Solution for C#
Public class Document: readFile, writeFile
//Implicit implementation
//explicit implementation
Void writeFile.Read ()
65 | P a g e
Question Bank Solution for C#
{
If (r1! = null)
r1.Read ();
If (w1! = null)
w1.Read ();
d1.Read ();
d1.View ();
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();
66 | P a g e
Question Bank Solution for C#
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);
67 | P a g e
Question Bank Solution for C#
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:
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
}
public ByTwos()
{
start = 0;
val = 0;
}
68 | P a g e
Question Bank Solution for C#
class SeriesDemo
{
public static void Main()
{
ByTwos twoOb = new ByTwos ();
ISeries ob;
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;
69 | P a g e
Question Bank Solution for C#
}
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);
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 Test
70 | P a g e
Question Bank Solution for C#
int x;
x = int.Parse(Console.ReadLine());
try
catch (NotInRange e)
Console.WriteLine(e.Message);
Console.Read();
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 };
71 | P a g e
Question Bank Solution for C#
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;
using System;
Class TestStatus
int c=0;
72 | P a g e
Question Bank Solution for C#
Console.Write (―Enter the status:-----‖);
Try
c=int.Parse (Console.ReadLine());
If (c>6)
Else
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)
{
73 | P a g e
Question Bank Solution for C#
If (num [j-1]>num [j])
n=num [j-1];
num [j]=n;
Console.WriteLine (num[i]);
}
public static void Main()
{
int [] a = new int [10];
Console.WriteLine (―Enter 10 numbers‖);
Try
Catch (IndexOutOfRangeException e)
}
}
74 | P a g e
Question Bank Solution for C#
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 Test
string x;
x = Console.ReadLine ();
try
If (x.Length>15)
catch (LengthException e)
Console.WriteLine (e.Message);
Console.Read ();
75 | P a g e
Question Bank Solution for C#
}
Q.66 Create a delegate DirectionDef and a class Direct that defines 4 methods:
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;
class Direct
76 | P a g e
Question Bank Solution for C#
public static void South()
{ t[i].Invoke() ; }
class TestDirection
int i=int.Parse(Console.ReadLine());
t1.IdentifyDirection ();
t1.show (i);
Console.Read ();
77 | P a g e
Question Bank Solution for C#
}
Q.67 Create a delegate strMod of string type. Create a class DelegateTest having three static 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.");
For (j=0, i=a.Length-1; i >= 0; i--, j++)
temp += a[i];
return temp;
}
78 | P a g e
Question Bank Solution for C#
StrMod strOp = new StrMod (replaceSpaces);
string str;
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.");
79 | P a g e
Question Bank Solution for C#
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;
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:
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)
{
80 | P a g e
Question Bank Solution for C#
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;
}
// Set up multicast.
strOp = replaceSp;
strOp += reverseStr;
// Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
// Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
81 | P a g e
Question Bank Solution for C#
// Remove space and add reverse.
strOp -= removeSp;
strOp += reverseStr;
// 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:
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)
82 | P a g e
Question Bank Solution for C#
{
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 ();
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;
83 | P a g e
Question Bank Solution for C#
class test
float num;
public test()
num = 3F;
public test(float x)
num=x;
c.num=a.num+b.num;
return(c);
c.num=a.num-b.num;
return(c);
84 | P a g e
Question Bank Solution for C#
c.num=a.num*b.num;
return(c);
c.num=a.num/b.num;
return(c);
string s = num.ToString();
class testdemo
ex1.show();
ex2.show();
85 | P a g e
Question Bank Solution for C#
ex3.show();
ex4.show();
ex5.show();
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 Matrix()
{}
m=r;n=c;
86 | P a g e
Question Bank Solution for C#
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
arr[i,j]=int.Parse(Console.ReadLine());
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];
87 | P a g e
Question Bank Solution for C#
}
else
Environment.Exit(-1);
return temp;
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];
88 | P a g e
Question Bank Solution for C#
else
Environment.Exit(-1);
return temp;
if(m1.n==m2.m)
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++)
else
89 | P a g e
Question Bank Solution for C#
Console.WriteLine("Matrix Size not Suitable");
Environment.Exit(-1);
return temp;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
Console.Write("\t"+arr[i,j]);
Console.WriteLine();
class TestMatrix
90 | P a g e
Question Bank Solution for C#
Matrix m2=new Matrix(2,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:
A. using System;
// A three-dimensional coordinate class.
class ThreeD
{
int x, y, z; // 3-D coordinates
public ThreeD() { x = y = z = 0; }
91 | P a g e
Question Bank Solution for C#
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 ();
92 | P a g e
Question Bank Solution for C#
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; }
93 | P a g e
Question Bank Solution for C#
// 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 ();
c = a + b; // object + object
Console.Write ("Result of a + b: ");
c.show ();
Console.WriteLine();
c = 15 + b; // int + object
Console.Write ("Result of 15 + b: ");
c.show ();
}
}
94 | P a g e
Question Bank Solution for C#
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: ");
95 | P a g e
Question Bank Solution for C#
c.show();
Console.WriteLine();
Q.76 Create a class Mystring which has a show method to display string. Overload operator :
96 | P a g e
Question Bank Solution for C#
{
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()
97 | P a g e
Question Bank Solution for C#
{
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);
}
}
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).
98 | P a g e
Question Bank Solution for C#
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;
99 | P a g e
Question Bank Solution for C#
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);
}
}
100 | P a g e