c sharp lab manual.pdf

25
Web Programming and C# Lab Manual Prepared By Miss Sujala V.Koparde

Upload: sujala-v-koparde

Post on 23-Oct-2015

1.631 views

Category:

Documents


150 download

DESCRIPTION

c# and Web Lab manual for BCA

TRANSCRIPT

Page 1: c  sharp lab manual.pdf

Web Programming and

C# Lab Manual

Prepared By

Miss Sujala V.Koparde

Page 2: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

C# is a computer language that can be studied on its own, it has a special relationship to its runtime environment, the .NET Framework .

C# language offers the following 1. No pointers required

C# programs typically have no need for direct pointer manipulation

2. Automatic memory management through garbage collection

Given this, C# does not support a delete keyword

3. Formal syntactic constructs for enumerations, structures, and class properties

4. The C++-like ability to overload operators for a custom type, without the complexity

5. As of C# 2005, the ability to build generic types and generic members using a syntax

very similar to C++ templates

6. Full support for interface-based programming techniques

7. Full support for aspect-oriented programming (AOP) techniques via attributes

What Is the .NET Framework? The .NET Framework defines an environment that supports the development and

execution of highly distributed, component-based applications. It enables differing computer languages to work together and provides for security,

program portability, and a common programming model for the Windows platform.

As it relates to C#, the .NET Framework defines two very important entities. The first is the Common Language Runtime (CLR). This is the system that manages the

execution of your program. The second entity is the .NET class library. This library gives your program access to the

runtime environment.

Page 3: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

1. Write a C# Program to accept a string and then check whether each word is palindrome or not.

The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements

WriteLine( ) pumps a text string (including a carriage return) to the output stream. ReadLine( ) allows you to receive information from the input stream up until the

carriage return.

Page 4: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

//Write a C# Program to accept a string and then check whether each word is palindrome or not. using System; class program {

static bool IsPalindrom(String s) {

bool plndm = true; for(int i=0;i<s.Length/2;i++) {

if(s[i]!=s[s.Length-i-1]) {

plndm=false; break;

} }

return plndm; } static void Main(string[] args) {

Console.WriteLine("enter a string"); String s=Console.ReadLine(); if(IsPalindrom(s)==true) { Console.WriteLine(s+" is a palindrome"); } else { Console.WriteLine(s+" is not palindrome"); }

} } OUTPUT D:\bca>csc palindrome.cs D:\bca> palindrome enter a string gadag gadag is a palindrome D:\bca> palindrome enter a string banahatti banahatti is not palindrome

Page 5: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

2. Write a C# program to demonstrate a basic calculator using command line arguments.

A command-line argument is the information that directly follows the program’s name on the command line when it is executed.

For C# programs, these arguments are then passed to the Main( ) method. To receive the arguments, you must use one of these forms of Main( ):

static void Main(string[ ] args) -returns void OR static int Main(string[ ] args) –returns int

For both, the command-line arguments are stored as strings in the string array passed to Main( ).

The length of the args array (args.Length) will be equal to the number of command-line arguments

Here static method called Parse( ) is used that converts a numeric string into its corresponding binary equivalent.

Page 6: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

//Write a C# program to demonstrate a basic calculator using command line arguments.

using System; class Calculator { public static void Main(string[] args) { double result=0; if(args.Length<3) Console.WriteLine("Pass 3 arguments:number1 operator number2"); else { double a=double.Parse(args[0]); string choice=args[1]; double b=double.Parse(args[2]); switch(choice) { case "+": result=a+b; break; case "-": result=a-b; break; case "*": result=a*b; break; case "/": result=a/b; break; default : Console.WriteLine("Operation Not Possible"); break; } Console.WriteLine("Result:{0}",+result); } } } OUTPUT: C:\bca>Calculator 12 * 2 Result:24 C:\bca>Calculator 3 + 6 Result:9 C:\bca>Calculator 2 # 1 Operation Not Possible Result:0 C:\bca16>Calculator 9 / 0 Result:Infinity

Page 7: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

3. Write a C# program to input real numbers and find the mean, variance and standard deviation. mean=∑x[i] variance=∑(x[i]-mean)2

------- ------------------- N N Standard devation=√variance The Math Class defines several standard mathematical operations, such as square root,

sine, cosine,and logarithms. The Math class is static, which means all of the methods defined by Math are static and no object of type Math can be constructed.

public static double Pow(double x,double y) -Returns x raised to the y power(xy). public static double Sqrt(double d)- Returns the square root of d.

Page 8: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to input real numbers and find the mean, variance and standard deviation.

using System; class pgm3 { public static void Main() { float[] x=new float[10]; int i, n; double avrg, var, SD, sum = 0, sum1 = 0; Console.WriteLine("Enter the value of N\n"); n = int.Parse(Console.ReadLine()); Console.WriteLine("Enter {0} real numbers\n", n); for (i = 0; i < n; i++) { x[i] = float.Parse(Console.ReadLine()); } /* Compute the sum of all elements */ for (i = 0; i < n; i++) { sum = sum + x[i]; } avrg = sum / (float)n; /* Compute varaience and standard deviation */ for (i = 0; i < n; i++) { sum1 = sum1 + Math.Pow((x[i] - avrg), 2); } var = sum1 / (float)n; SD = Math.Sqrt(var); Console.WriteLine("Mean of all elements = {0}\n", avrg); Console.WriteLine("Variance of all elements = {0}\n", var); Console.WriteLine("Standard deviation = {0}\n", SD); Console.ReadLine(); } /*End of main()*/ }

Page 9: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

OUTPUT Enter the value of N 6 Enter 6 real numbers 12 34 10 50 42 33 Mean of all elements = 29.66 Variance of all elements = 213.89 Standard deviation = 14.62

Page 10: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

4.Write a C# program to demonstrate boxing and unboxing concepts. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Converting value type to reference type is called boxing by storing the variable in a

System.Object. When a variable of a value type needs to be converted to a reference type, an object box on heap is allocated to hold the value, and the value is copied into the box.

Converting reference type to value type to called unboxing. Unboxing is just opposite. When an object box is cast back to its original value type, the value is coped out of the box and into the appropriate storage location

Page 11: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to demonstrate boxing and unboxing concepts. using System; class Boxing { public static void Main(String[] a) { int m=10; Object om=m; m=20; Console.WriteLine("*************BOXING*************"); Console.WriteLine("m="+m); Console.WriteLine("om="+om); Console.ReadLine(); int n=10; Object on=n; int x=(int)on; Console.WriteLine("**********UNBOXING***********"); Console.WriteLine("n="+n); Console.WriteLine("on="+on); Console.ReadLine(); } } OUTPUT *************BOXING************* m=20 om=10 **********UNBOXING*********** n=10 on=10

Page 12: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

5. Write a C# program to show the machine details like machine name, Operating System, Version, Physical Memory and calculate the time since the Last Boot Up.(Hint: Use System.Environment Class). Environment Class

It provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited. The Environment type exposes the following members. Properties

Name Description

MachineName Gets the NetBIOS name of this local computer.

OSVersion Gets an OperatingSystem object that contains the current platform identifier and version number.

WorkingSet Gets a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.

TickCount Gets the number of milliseconds elapsed since the last Boot Up The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.

Page 13: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to show the machine details like machine name, Operating System, Version, Physical Memory and calculate the time since the Last Boot Up.(Hint: Use System.Environment Class)

using System; class Exp {

public static void Main() {

//Machine Name Console.WriteLine("MachineName:{0}",Environment.MachineName); //OS running this application? Console.WriteLine("current os:{0}",Environment.OSVersion); //Gets the amount of physical memory mapped to the process Context Console.WriteLine("working Set:{0}",Environment.WorkingSet); //The amount of time is milliseconds that has passed since the last Console.WriteLine("tickCount:{0}",Environment.TickCount); }

} OUTPUT C:\bca16>Exp MachineName:PC-1 current os:Microsoft Windows NT 6.1.7600.0 working Set:10256384 tickCount:1112131

Page 14: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

6. Write a C# program to find the sum of all the elements present in jagged arrays of 3 inner layers. C# also supports two varieties of multidimensional arrays.

1) Rectangular array: It is simply an array of multiple dimensions, where each row is of the same length.

2) Jagged array: It is often called array of arrays. An element of a jagged array itself is an array. Thus, a jagged array can be used to create a table in which the lengths of the rows are not the same.

For example, jagged arrays is an array of integers containing another array of integers. int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} }

Page 15: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to find the sum of all the elements present in jagged arrays of 3 inner layers.

using System; public class JaggedArrayDemo { public static void Main() { int sum = 0; int[][] arr = new int[3][]; arr[0] = new int[3]; arr[1] = new int[5]; arr[2] = new int[2]; for (int i = 0; i < arr.Length; i++) { Console.WriteLine("Enter the Size of the Inner Array " + (i + 1) + " : "); arr[i] = new int[int.Parse(Console.ReadLine())]; Console.WriteLine("Enter elements for Inner Array " + (i + 1) + " : "); for (int j = 0; j < arr[i].Length; j++) { arr[i][j] = int.Parse(Console.ReadLine()); sum += arr[i][j]; } } for (int i = 0; i < arr.Length; i++) { Console.Write("Length of row {0} is {1}:\t", i, arr[i].Length); for (int j = 0; j < arr[i].Length; j++) Console.Write(arr[i][j] + " "); Console.WriteLine(); } Console.WriteLine("The Sum is = " + sum); } }

Page 16: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

OUTPUT Enter the Size of the Inner Array 2 : 3 Enter elements for Inner Array 2 : 4 5 2 Enter the Size of the Inner Array 3 : 4 Enter elements for Inner Array 3 : 2 6 4 3 Length of row 0 is 2: 2 3 Length of row 1 is 3: 4 5 2 Length of row 2 is 4: 2 6 4 3 The Sum is = 31

Page 17: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

7. Write a C# program to find the second largest element in a single dimension array.

An array is a set of data items, accessed using a numerical index.n C#, an array index starts at zero. That means, first item of an array will be stored at 0th position. The position of the last item on an array will total number of items - 1.

In C#, arrays are objects. That means declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator. For example The following code declares an array, which can store 5 items starting from index 0 to 4. int [] intArray; intArray = new int[5];

Page 18: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to find the second largest element in a single dimension array. using System; class SLar

{ int size; int[] nums; int lar, sec; public SLar(int n) {

nums=new int[size=n]; } public void input() {

Console.WriteLine("Enter the Elements of the array"); for (int i = 0; i < size; i++) nums[i] = int.Parse(Console.ReadLine());

} public int second() {

lar = nums[0]; sec = nums[1]; for (int i = 0; i < size; i++) {

if (nums[i] > lar) { sec = lar; lar = nums[i]; } if ((sec < nums[i] && nums[i] > lar || (nums[i] != lar && sec == lar))) sec = nums[i];

} if(sec==lar) return -1; else return sec;

} } class SLarMain {

public static void Main() { Console.WriteLine("Enter the Size of Array"); SLar s = new SLar(int.Parse(Console.ReadLine())); s.input(); Console.WriteLine((s.second() == -1 ? "\nAll Elements are Equal" : "\nSecond Largest=" +s.second()));

} }

Page 19: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

OUTPUT Enter the Size of Array 5 Enter the Elements of the array 34 25 56 67 67 Second Largest=56

Page 20: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

8. Write a C# program to demonstrate the use of out and ref variables.

C# provides a set of parameter modifiers that control how arguments are sent into(and returned from) a given method.

Page 21: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Write a C# program to demonstrate the use of out and ref variables. using System; class Pr8 {

//use of out variables public static void GetStrings(out string s1,out string s2) {

Console.WriteLine("enter the string s1"); s1=Console.ReadLine(); Console.WriteLine("enter the string s2"); s2=Console.ReadLine();

} //use of ref variables public static void SwapString(ref string s1,ref string s2) {

string tempstr=s1; s1=s2; s2=tempstr;

} static void Main(string[] args) {

string s1,s2; //Read Strings GetStrings(out s1,out s2); Console.WriteLine("before:{0},{1}",s1,s2); //Swap Strings SwapString(ref s1,ref s2); Console.WriteLine("after:{0},{1}",s1,s2);

} } OUTPUT D:\bca6>pr8 enter the string s1 stc enter the string s2 bca before:stc,bca after:bca,stc

Page 22: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

9. Create C# program with a Class named Employee and attributes like SSN, Name, Address, DOB, Sex, Salary, Age. This class must also perform adding and deleting of employees with following constrains a. Using properties validate date of birth of employee and also calculate the age automatically. b. The program must also have a method which calculates the gross salary by taking basic salary as input.

Page 23: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

10. Using Try, catch and Finally block, write a program in C# to demonstrate error handling.

Exceptions: Exceptions are typically regarded as runtime anomalies. The Atoms of .NET Exception Handling(interrelated entities)

1. A class type that represents the details of the exceptional circumstance. 2. A method that throws an instance of the exception to the caller 3. A block of code that will invoke the exception method 4. A block of code that will process(or catch) the exception

The Finally Block,

A try/catch scope may also define an optional finally block. The motivation behind a finally block is to ensure that a set of code statements will always execute, exception (of any type) or not.

Page 24: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

// Using Try, catch and Finally block, write a program in C# to demonstrate error handling.

using System; class Radio {

public void TurnOn(bool on) { if(on) Console.WriteLine("Jamming..."); else Console.WriteLine("Quiet time...");

} } class Car {

public const int MaxSpeed=100; private int currSpeed; private string petName; private bool carIsDead; private Radio theMusicBox=new Radio(); public Car(){} public Car(string name,int currSp) { currSpeed=currSp; petName=name;

} public void CrankTunes(bool state) { theMusicBox.TurnOn(state);

} public void Accelerate(int delta) { if(carIsDead) Console.WriteLine("{0} is out of order...",petName); else { currSpeed+=delta; if(currSpeed>MaxSpeed) { carIsDead=true; currSpeed=0; throw new Exception(string.Format("{0} has overheated!",petName)); } else Console.WriteLine("=>CurrSpeed={0}",currSpeed); }

} static void Main(string[] args) {

Page 25: c  sharp lab manual.pdf

BCA507: Web Programming and C# Lab

Console.WriteLine("*****Simple Exception Example*****"); Console.WriteLine("=>creating a car and stepping on it!"); Car myCar=new Car("Zippy",20); myCar.CrankTunes(true); try { for(int i=0;i<10;i++) myCar.Accelerate(10);

} catch(Exception e) { Console.WriteLine("\n*****Error!*****"); Console.WriteLine("Method:{0}",e.TargetSite); Console.WriteLine("Message:{0}",e.Message); Console.WriteLine("Source:{0}",e.Source);

} finally { myCar.CrankTunes(false); Console.WriteLine("Radio has been TurnedOff");

} }

} OUTPUT *****Simple Exception Example***** =>creating a car and stepping on it! Jamming... =>CurrSpeed=30 =>CurrSpeed=40 =>CurrSpeed=50 =>CurrSpeed=60 =>CurrSpeed=70 =>CurrSpeed=80 =>CurrSpeed=90 =>CurrSpeed=100 *****Error!***** Method:Void Accelerate(Int32) Message:Zippy has overheated! Source:Car Quiet time... Radio has been TurnedOff