41
Practical No: 01 Write a program that would illustrate concept of declaration and initialization of value type variables. Use the following literals for initializing the variables. ‘A’ 50 123456789 1234567654321 True 0.000000345 1.23e.5 using System; class ValueTypeDemo { public static void Main() { char c = 'A'; byte b = 50; int i = 123456789; long l = 123456754321; bool bl = true; double d = 0.000000345; float g = 1.23e5f; Console.WriteLine("The charecter value type variable holds " + c + " value"); Console.WriteLine("The byte value type variable holds " + b + " value"); Console.WriteLine("The integer value type variable holds " + i + " value"); Console.WriteLine("The long value type variable holds " + l + " value"); Console.WriteLine("The boolean value type variable holds " + bl + " value");

C# Program Main

Embed Size (px)

Citation preview

Page 1: C# Program Main

Practical No: 01

Write a program that would illustrate concept of declaration and initialization of value type variables. Use the following literals for initializing the variables.

‘A’ 50 123456789 1234567654321 True 0.000000345 1.23e.5

using System;class ValueTypeDemo{

public static void Main(){

char c = 'A';byte b = 50;int i = 123456789;long l = 123456754321;bool bl = true;double d = 0.000000345;float g = 1.23e5f;

Console.WriteLine("The charecter value type variable holds " + c + " value");Console.WriteLine("The byte value type variable holds " + b + " value");Console.WriteLine("The integer value type variable holds " + i + " value");Console.WriteLine("The long value type variable holds " + l + " value"); Console.WriteLine("The boolean value type variable holds " + bl + " value"); Console.WriteLine("The double value type variable holds " + d + " value"); Console.WriteLine("The float value type variable holds " + g + " value"); Console.ReadLine();

}}Output:

The charecter value type variable holds A valueThe byte value type variable holds 50 valueThe integer value type variable holds 123456789 valueThe long value type variable holds 123456754321valueThe boolean value type variable holds True valueThe double value type variable holds 3.34E-07 valueThe float value type variable holds 123000 valuePractical No: 02

Page 2: C# Program Main

Write a program to read interactively two integer & two double values using methods Console.ReadLine() , int.Parse() and double.Parse() methods and then display their

Sum Product Difference Integer division Modulus division

using System;class Program{

public static void Main(string[] args){

int x, y;float a, b;Console.WriteLine("Enter two integer numbers");x = int.Parse(Console.ReadLine());y = int.Parse(Console.ReadLine());Console.WriteLine("Enter two float numbers");a = float.Parse(Console.ReadLine());b = float.Parse(Console.ReadLine());

Console.WriteLine("The sum of two integer numbers is " + (x + y)); Console.WriteLine("The difference of two integer numbers is " + (x - y));Console.WriteLine("The product of two integer numbers is " + (x * y));Console.WriteLine("The division of two integer numbers is " + (x / y));Console.WriteLine("The remainder of two integer numbers is " + (x % y)); Console.WriteLine("***********************************************************");Console.WriteLine("The sum of two float numbers is " + (a + b));Console.WriteLine("The difference of two float numbers is " + (a - b)); Console.WriteLine("The product of two float numbers is " + (a * b)); Console.WriteLine("The division of two float numbers is " + (a / b)); Console.WriteLine("The remainder of two float numbers is " + (a % b));Console.ReadLine();}

}

Output:

Enter two integer numbers

Page 3: C# Program Main

23Enter two float numbers2.53.5The sum of two integer numbers is 5The difference of two integer numbers is -1The product of two integer numbers is 6The division of two integer numbers is 0The remainder of two integer numbers is 2***********************************************************The sum of two float numbers is 6The difference of two float numbers is -1 The product of two float numbers is 8.75 The division of two float numbers is 0.7142857 The remainder of two float numbers is 2.5

Practical No: 03

Page 4: C# Program Main

Write a program to convert the given temperature in Fahrenheit to Celsius using the following conversion formula C= (F-32)/1.8

using System;class Temperature{

public static void Main(){

float fahrenheit,celcius;string s;Console.Write("Enter the temperature in fahrenheit : ");s = Console.ReadLine();fahrenheit = float.Parse(s);celcius = (float)((fahrenheit-32)/1.8);Console.WriteLine("The Temperature in celcius = " +celcius);Console.ReadLine();

}}

Output:Enter the temperature in fahrenheit : 98Temperature in celcius = 36.66667

Practical No: 04

Page 5: C# Program Main

Admission to a professional course is subject to the following conditions:

Marks in mathematics >= 60 Marks in physics >= 50 Marks in chemistry >= 40 Total in all three subjects >= 200

(Or) Total in mathematics and physics>=150

Given the marks in the three subjects, write a program to process the application to list the eligible candidates.

using System;class Admission{

public static void Main(){

float mksMaths, mksPhysics, mksChemistry, mksTotal, MathsPhysics;int response;beginning:Console.WriteLine(""); Console.WriteLine(" ********** Students Enrollment Checking Criteria ********** ");Console.WriteLine(""); Console.Write("Enter the marks in Maths : ");mksMaths = float.Parse(Console.ReadLine());

Console.Write("Enter the marks in Chemistry : ");mksChemistry = float.Parse(Console.ReadLine());

Console.Write("Enter the marks in Physics : ");mksPhysics = float.Parse(Console.ReadLine());

mksTotal = (float)(mksMaths + mksChemistry + mksPhysics);MathsPhysics = (float)(mksMaths + mksPhysics);if ((mksMaths >= 60 && mksPhysics >= 50 && mksChemistry >= 40) || (mksTotal >=200 || (mksMaths + mksPhysics) >= 150)){

Console.WriteLine("Congratulations !!! The candidate is selected ... ");}else{

Console.WriteLine("Sorry, The candidate is rejected ... Better luck for next year.");

}

Page 6: C# Program Main

Console.WriteLine(""); Console.Write("Enter 1 for next candidate, 0 to exit : ");response = int.Parse(Console.ReadLine());if (response == 1)goto beginning;elsegoto end;end:Console.ReadLine();}

}

Output:

********** Students Enrollment Checking Criteria **********Enter the marks in Maths : 50Enter the marks in Chemistry: 40Enter the marks in Physics: 35Sorry, The candidate is rejected ... Better luck for next year.Enter 1 for next candidate, 0 to exit: 1********** Students Enrollment Checking Criteria **********Enter the marks in Maths : 70Enter the marks in Chemistry: 80Enter the marks in Physics: 85Congratulations!!! The candidate is selected...Enter 1 for next candidate, 0 to exit: 0

Practical No: 05

Write a program that will read the value of x and evaluate the following function

Page 7: C# Program Main

{1 for x>0Y= {0 for x=0

{-1 for x<0Using

Nested if statements Else if statements, and Conditional operator?

using System;class ChangingValuesOfY{

public static void Main(){

int x,y;Console.Write("Enter the value of x : ");x = int.Parse(Console.ReadLine());Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(" ********* Changing values of Y by nested ifstatements *********");Console.WriteLine(""); if (x != 0){

if (x > 0){

Console.WriteLine("Y = 1");}if (x < 0){

Console.WriteLine("Y = -1");}

}else{

Console.WriteLine("Y = 0");}

Console.WriteLine(""); Console.WriteLine(" ********* Changing values of Y by else ifstatements *********");Console.WriteLine(""); if (x == 0){

Console.WriteLine("Y = 0");}else if(x > 0){

Page 8: C# Program Main

Console.WriteLine("Y = 1");}else{

Console.WriteLine("Y = -1");}Console.WriteLine(""); Console.WriteLine(" ********* Changing values of Y by conditionaloperator *********");Console.WriteLine(""); y = (x != 0)?((x>0)?1:-1):0;Console.WriteLine("Y = "+y);Console.ReadLine();

}}

Output:Enter the value of x : 2********* Changing values of Y by nested if statements *********Y = 1********* Changing values of Y by else if statements *********Y = 1********* Changing values of Y by conditional operator *********Y = 1

Practical No: 06(a)

Write a program to draw following output

Page 9: C# Program Main

using System;class Pattern{ public static void Main() { int i, j, num = 5, k; for (i = 5; i >= 1; i--) { for (k = num; k >= i; k--) { Console.Write(" "); } for (j = 1; j <= i; j++) { Console.Write("#"); } Console.WriteLine(); } Console.ReadLine(); }}

Output:

##### #### ### ## #

Practical No: 06(b)

Write a program to draw following output

Page 10: C# Program Main

using System;class FloydsTriangle1{

public static void Main(){

int i,j,k=1;for (i=1; i<=4; i++){

for (j=1; j<i+1; j++){

Console.Write(k++ + " "); }Console.Write("\n");

}Console.ReadLine();}

}

Output:

12 34 5 67 8 9 10

Practical No: 06(c)

Write a program to draw following output

Page 11: C# Program Main

using System;class PyramidNumbers{

public static void Main(){

int i,j,num=5,k;for(i=1;i<=num;i++){

for(k=num;k>=i;k--){

Console.Write(" ");}for(j=1;j<=i;j++) {

Console.Write(" " +i); }Console.Write("\n");

}Console.ReadLine();

}}

Output:

1 2 2 3 3 3 4 4 4 45 5 5 5 5

Practical No: 06(d)

Write a program to draw following output

Page 12: C# Program Main

using System;class pascalTriangle{ public static void Main() { int binom = 1, q = 0, r, x; Console.WriteLine("Enter the number of rows"); string s = Console.ReadLine(); int p = Int32.Parse(s); Console.WriteLine(p); Console.WriteLine("The Pascal Triangle"); while (q < p) { for (r = 40 - (3 * q); r > 0; --r) Console.Write(""); for (x = 0; x <= q; ++x) { if ((x == 0) || (q == 0)) binom = 1; else binom = (binom * (q - x + 1)) / x; Console.Write(binom); } Console.Write("\n"); ++q; } Console.ReadLine(); }}

Output:

Enter the number of rows5The Pascal Triangle111121133114641

Practical No: 07

Page 13: C# Program Main

Write a method that would calculate the values of money for the given period of years and print the results giving the following details on one time of output:

Principle amount Interest rate Period in years Final value

The method takes principle amount, Interest rate and Period as input parameters and does not return any value. The following formula may be used respectively:

Value of the end of year = Value at start of year (1+interest rate)Write a program to test the method

using System; class Program { public void calculate() { decimal p, n, r, amt, val; Console.WriteLine("Enter the Principle Amount "); p = decimal.Parse(Console.ReadLine()); Console.WriteLine("Enter the number of year "); n = decimal.Parse(Console.ReadLine()); Console.WriteLine("Enter the rate of interest "); r = decimal.Parse(Console.ReadLine());

amt = (p * n * r) / 100; Console.WriteLine("The interest amount is " + amt); val = p * (1 + r); Console.WriteLine("The value at the end of year is " + val); } } class test { public static void Main() { Program p = new Program(); p.calculate(); Console.ReadLine(); } }

Page 14: C# Program Main

Output:

Enter the Principle Amount1000Enter the number of years2Enter the rate of interest10The interest amount is 200The value at the end of the year is 11000

Practical No: 08

Page 15: C# Program Main

Write a method that takes an array as an input parameter and uses two methods, one to find the largest array element and other to compute the average of array elements.

using System;class ArrayFunction{ public static void Main() { int Largest; double Average; int c; int num; int[] array1; Console.Write("Enter the number of Elements in an Array : "); c = Int32.Parse(Console.ReadLine()); array1 = new int[c]; for (int i = 0; i < c; i++) { Console.WriteLine("Enter the element " + i); num = Int32.Parse(Console.ReadLine()); array1[i] = num; } foreach (int i in array1) { Console.Write(" " + i); } Console.WriteLine(); Largest = Large(array1); Average = Avg(array1); Console.WriteLine("\n The largest element in the array is " + Largest); Console.WriteLine("The Average of elements in the array is " + Average); Console.ReadLine(); } // Determining the largest array element static int Large(params int[] arr) { int temp = 0; for (int i = 0; i < arr.Length; i++) { if (temp <= arr[i]) { temp = arr[i]; } }

Page 16: C# Program Main

return (temp); } // Determining the average of array elements static double Avg(params int[] arr) { double sum = 0; for (int i = 0; i < arr.Length; i++) { sum = sum + arr[i]; } sum = sum / arr.Length; return (sum); }}

Output:

Enter the number of Elements in an Array : 3Enter the element 03Enter the element 14Enter the element 25 3 4 5

The largest element in the array is 5The Average of elements in the array is 4

Page 17: C# Program Main

Practical No: 09

Write a C# program that uses an array of five items of data type designed in

using System;using System.Collections.Generic;using System.Linq;using System.Text;

class program{ struct student { public int code; public string name; public int cost; public int qty; public int totalitems; } public static void Main() { student[] s1 = new student[5]; for (int i = 1; i <= 5; i++) { Console.WriteLine("Enter the " +i +" item's code"); s1[i].code = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the " +i +" item's name"); s1[i].name = Console.ReadLine(); Console.WriteLine("Enter the " +i +" item's cost"); s1[i].cost = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the " +i +" item's qty"); s1[i].qty = int.Parse(Console.ReadLine()); s1[i].totalitems = s1[i].cost * s1[i].qty; } Console.WriteLine("Code\tName\tCost\tqty\tTotal_Items"); for (int i = 0; i < 5; i++) { Console.WriteLine(s1[i].code + "\t" + s1[i].name + "\t" + s1[i].cost + "\t" + s1[i].qty + "\t" + s1[i].totalitems); } Console.ReadLine(); }

}

Page 18: C# Program Main

Output:

Enter the 1 item's code235Enter the 1 item's nameFanEnter the 1 item's cost350Enter the 1 item's qty5

Enter the 2 item's code236Enter the 2 item's nameTrolleyEnter the 2 item's cost250Enter the 2 item's qty3

Enter the 3 item's code237Enter the 3 item's nameWashing-MachineEnter the 3 item's cost5000Enter the 3 item's qty1

Enter the 4 item's code238Enter the 4 item's nameAir-ConditionerEnter the 4 item's cost20000Enter the 4 item's qty2

Enter the 5 item's code239Enter the 5 item's namePen-DriveEnter the 5 item's cost750Enter the 5 item's qty10

Page 19: C# Program Main

Code Name Cost Qty Total_Items

235 Fan 350 5 1750236 Trolley 250 3 750237 Washing-Machine 5000 1 5000238 Air-Conditioner 20000 2 40000239 Pen-Drive 750 10 7500

Page 20: C# Program Main

Practical No: 10

Design a class to represent a bank account. Include the following members:

Data members: Name of the depositor Account number Type of account Balance amount in the account

Members:

To assign initial values To deposit an amount To withdraw an amount after checking balance To display the name and balance

using System;class Account{ public string Name; public int Account_No; public string Account_Type; public double Balance; public double D_amt; public double W_amt;

public void Initial_info() { Console.WriteLine("Enter the name of depositor"); Name = Console.ReadLine(); Console.WriteLine("Enter Account Number"); Account_No = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Type of Account"); Account_Type = Console.ReadLine(); Console.WriteLine("Enter initial Balance"); Balance = double.Parse(Console.ReadLine()); } public void Deposite() { Console.WriteLine("Enter the amount to be deposited"); D_amt = double.Parse(Console.ReadLine()); Balance = Balance + D_amt; }

Page 21: C# Program Main

public void Withdraw() { Console.WriteLine("The Balance is " + Balance); Console.WriteLine("Enter the amount to withdraw"); W_amt = double.Parse(Console.ReadLine()); Balance = Balance - W_amt; } public void display() { Console.WriteLine("The Name of the Account Holder is " + Name); Console.WriteLine("The Total balance is " + Balance); }}

class Test{ static void Main() { Account acct = new Account(); acct.Initial_info(); String c = "Y"; do { Console.WriteLine("****MENU****"); Console.WriteLine("1:Deposite"); Console.WriteLine("2:Withdraw"); Console.WriteLine("3:Balance Enquiry"); Console.WriteLine("Enter Your Choice"); int ch = int.Parse(Console.ReadLine()); switch (ch) { case 1: Console.Clear(); acct.Deposite(); break; case 2: Console.Clear(); acct.Withdraw(); break; case 3: Console.Clear(); acct.display(); break; }

Page 22: C# Program Main

Console.Clear(); Console.WriteLine("Do You Wnat to continue"); c = Console.ReadLine(); } while ((c == "Y") || (c == "N")); Console.ReadLine(); }}

Output:

Enter the name of depositorAbcEnter the Account Number12345Enter the Type of AccountSavingEnter initial balance40000****MENU****1; deposit2: Withdraw3: Balance EnquiryEnter your choice 1Enter Amount to be deposited4000Do you want to continue?N

Page 23: C# Program Main

Practical No: 11

Create base class called Shape. Use this class to store two double type values that could be used to compute the area of figures.

Derive two specialized classes called triangle and rectangle from the base Shape. Add to the base class, a method Set to initialize base class data members and

another method Area to compute and display the area of figures. Make Area as virtual method and redefine this method suitable in the derived class.

Using these classes, design a program that will accept dimensions of a triangle or rectangle interactively and display the area.

using System;using System.Collections.Generic;using System.Linq;using System.Text;

class Shape{ public double a; public double b; public void Set(double x, double y) { Console.WriteLine("Enter 2 values: "); x = double.Parse(Console.ReadLine()); y= double.Parse(Console.ReadLine()); a = x; b = y; } public virtual void Area() { Console.WriteLine("Area"); } class Triangle : Shape { public override void Area() { Console.WriteLine("The Area of Triangle is " + (0.5 * a * b)); } } class Rectangle : Shape { public override void Area() { Console.WriteLine("The Area of Rectangle is " + a * b);

Page 24: C# Program Main

} } class Test { public static void Main() { Shape sh = new Shape(); sh = new Triangle(); sh.Set(0, 0); sh.Area(); sh = new Rectangle(); sh.Set(0, 0); sh.Area(); Console.ReadLine(); } }}

Output:

Enter 2 values:45The Area of Triangle is 10

Enter 2 values:36The Area of Rectangle is 18

Page 25: C# Program Main

Program No: 12

Create a class name double this class contain three double number overload +,-,*, / operator so that they can be applied to the objects of class double. Write C# program to test it

using System;class OperatorOverload { double x, y; public OperatorOverload() { } public OperatorOverload(double a, double b) { x = a; y = b; } public static OperatorOverload operator +(OperatorOverload o1, OperatorOverload o2) { OperatorOverload o3 = new OperatorOverload(); o3.x = o1.x + o2.x; o3.y = o1.y + o2.y; return o3; } public static OperatorOverload operator -(OperatorOverload o1, OperatorOverload o2) { OperatorOverload o3 = new OperatorOverload(); o3.x = o1.x - o2.x; o3.y = o1.y - o2.y; return o3; } public static OperatorOverload operator *(OperatorOverload o1, OperatorOverload o2) { OperatorOverload o3 = new OperatorOverload(); o3.x = o1.x * o2.x; o3.y = o1.y * o2.y; return o3; } public static OperatorOverload operator /(OperatorOverload o1, OperatorOverload o2) { OperatorOverload o3 = new OperatorOverload(); o3.x = o1.x / o2.x; o3.y = o1.y / o2.y; return o3; } public void display() {

Page 26: C# Program Main

Console.WriteLine("x=" + x); Console.WriteLine("y=" + y); } public static void Main(string[] args) { OperatorOverload op1, op2, add, sub, mul, div; op1 = new OperatorOverload(1.1, 1.2); op2 = new OperatorOverload(1.3, 1.4); Console.WriteLine("Values of object1="); op1.display(); Console.WriteLine("Values of object2="); op2.display(); add = op1 + op2; Console.WriteLine("After overloading + operator values are="); add.display(); sub = op1 - op2; Console.WriteLine("After overloading - operator values are="); sub.display(); mul = op1 * op2; Console.WriteLine("After overloading * operator values are="); mul.display(); div = op1 / op2; Console.WriteLine("After overloading / operator values are="); div.display(); Console.ReadLine(); } }

Page 27: C# Program Main

Output:

Values of object1=x=1.1y=1.2Values of object2=x=1.3y=1.4After overloading + operator values are=x=2.4y=2.6After overloading - operator values are=x=-0.2y=-0.2After overloading * operator values are=x=1.43y=1.68After overloading / operator values are=x=0.846153846153846y=0.857142857142857

Page 28: C# Program Main

Practical No: 13

Write a program to create a delegate and event

using System;using System.Collections.Generic;using System.Linq;using System.Text;

public delegate void EDelegate(string str); class EventClass { //declaration of events public event EDelegate Status; public void TriggerEvent() { if(Status!=null ) Status ("Event Triggered"); } }class EventTest{ public static void Main(string[] args) { EventClass ec=new EventClass (); EventTest et = new EventTest(); ec.Status +=new EDelegate(et.EventCatch); ec.TriggerEvent (); Console.ReadLine(); } public void EventCatch(string str) { Console.WriteLine (str); } }

Output:Event Triggered

Page 29: C# Program Main

Practical No: 14

Write a program to print the integer 3456789 using the following format specifications:

a) Using the format Character Db) Using the format Character Nc) Using the format Character Ed) Using the Zero placeholdere) Using the pound Character

using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace formatnumber{ public class DecimalPoint { public static void Main() {

Console.WriteLine("Integer format"); Console.WriteLine("{0:D}", 3456789);

Console.WriteLine();

Console.WriteLine("Numbar format"); Console.WriteLine("{0:N}",3456789);

Console.WriteLine();

Console.WriteLine("Exponential Form"); Console.WriteLine("{0:###.000E-00}", 3456789);

Console.WriteLine(); Console.WriteLine("Zero place holder"); Console.WriteLine("{0:000}", 3456789);

Console.WriteLine();

Page 30: C# Program Main

Console.WriteLine("Pound character"); Console.WriteLine("{0:#####.000}",3456789);

Console.WriteLine();

Console.WriteLine("Comma"); Console.WriteLine("{0:#,###.##}",3456789);

Console.ReadLine();

Console.WriteLine(); } }

}

Output:

Integer format3456789

Numbar format3,456,789.00

Exponential Form345.679E04

Zero place holder3456789

Pound character3456789.000

Comma3,456,789

Page 31: C# Program Main

Practical No: 15

Develop a program that is likely to throw multiple exceptions that are handled using catch and finally block

using System;

using System.Collections.Generic;

using System.Text;

namespace MutipleCatch

{

class MultipleCatchBlockExample

{

public void execute()

{

try

{

double val1=0;

double val2=121;

Console.WriteLine("Dividing {0} by {1}",val1,val2);

Console.WriteLine("{0}/{1}={2}",val1,val2,DivideValues(val1,val2));

}

//most specific exception type first

catch(DivideByZeroException ex)

{

Console.WriteLine("DivideByZeroException caught!",ex);

}

Page 32: C# Program Main

catch(ArithmeticException e)

{

Console.WriteLine("ArithmeticException caught!",e);

}

//generic exception type last

catch

{

Console.WriteLine("Unknown Exception caught");

}

finally

{

Console.WriteLine("Exceptions are caught");

}

}

//do the division if legal

public double DivideValues(double val1,double val2)

{

if(val2==0)

{

DivideByZeroException dx=new DivideByZeroException();

Console.WriteLine(dx.Message);

}

if(val1==0)

{

ArithmeticException ax=new ArithmeticException();

Page 33: C# Program Main

Console.WriteLine(ax.Message);

}

return val1/val2;

}

static void Main(string[] args)

{

Console.WriteLine("This is an example of multiple catch and finally blocks and each catch block handle errors/exceptions of a certain type thrown in the application.\n");

MultipleCatchBlockExample mcbobj=new MultipleCatchBlockExample();

mcbobj.execute();

Console.ReadLine();

}

}

}

OUTPUT:

This is an example of multiple catch and finally blocks and each catch block handle errors/exceptions of a certain type thrown in the application.

Dividing 0 by 121

Overflow or underflow in the arithmetic operation.

0/121=0

Exceptions are caught