dot net labmanual1.1.doc - eduoncloudeduoncloud.com/sites/default/files/dotnet lab manual.pdf · 14...

46
DotNet Laboratory Eduoncloud.com MCA 5 th Semester Dept of RVCE MCA Page 1 CONTENTS SL. No. Description Page No. 1 VTU List of programs 4 2 Introduction to .Net 6 3 Write a Program in C# to check whether a number is Palindrome or not. 9 4 Write a Program in C# to demonstrate Command line arguments processing. 10 5 Write a Program in C# to find the roots of Quadratic Equation. 11 6 Write a Program in C# to demonstrate Boxing and unBoxing. 12 7 Write a Program in C# to implement Stack operations. 14 8 Write a Program to demonstrate Operator overloading. 16 9 Write a Program in C# to find the second largest element in a single dimensional array. 18 10 Write a Program in C# to multiply to matrices using Rectangular arrays. 21

Upload: lecong

Post on 23-Feb-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 1

CONTENTS

SL.

No. Description Page

No.

1 VTU List of programs 4

2 Introduction to .Net 6

3 Write a Program in C# to check whether a number is Palindrome or not. 9

4 Write a Program in C# to demonstrate Command line arguments processing. 10

5 Write a Program in C# to find the roots of Quadratic Equation. 11

6 Write a Program in C# to demonstrate Boxing and unBoxing. 12

7 Write a Program in C# to implement Stack operations. 14

8 Write a Program to demonstrate Operator overloading. 16

9 Write a Program in C# to find the second largest element in a single dimensional array. 18

10 Write a Program in C# to multiply to matrices using Rectangular arrays. 21

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 2

11 Find the sum of all the elements present in a jagged array of 3 inner arrays. 23

12 Write a Program to reverse a given string using C#. 25

13 Using Try, Catch and Finally blocks write a program in C# to demonstrate error handling. 26

14 Design a simple calculator using Switch Statement in C#. 28

15 Demonstrate Use Of Virtual and override keyword in C# with a simple Program. 30

16 Implement Linked Lists in C# using the existing collections name space. 32

17 Write a Program to demonstrate abstract class and abstract methods in C#. 36

18 Write a Program in C# to build a class which implements an interface which is already existing. 37

19 Write a Program to illustrate the use of different properties in C#. 39

20 Demonstrate arrays of interface types with a C# program. 41

21 Viva questions & extra programs 43

22 Lab Cycles 46

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 3

23 Lab instructions 48

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 4

Introduction to DotNet

.Net is a framework, which is a collection of tools, technologies, and languages all these work

together in a framework to provide the solutions that are needed to easily build and deploy truly

robust enterprise applications. It is not a operating system nor a programming language. It’s a

layer between the OS and the programming language. It consist of CLR (Common Language

Runtime), CTS (Common type System) and CLS (Common Language Specification).

.Net supports many programming languages like VB.NET,C# etc. It provides common set of

class libraries to .net based programming languages.

Here programs are executed using C# (pronounced "C sharp") programming language. C# is

almost same as Java. No pointers required. It manages the memory automatically. Supports

operator overloading and interface-based programming techniques. C# can produce code that can

run only on .NET environment.

Visual C# .NET is Microsoft's C# development tool. It includes an interactive development

environment, visual designers for building Windows and Web applications, a compiler, and a

debugger. Visual C# .NET is part of a suite of products, called Visual Studio .NET, that also

includes Visual Basic .NET, Visual C++ .NET, and the JScript scripting language.

Namespaces are the way to organize .NET Framework Class Library into a logical grouping

according to their functionality, usability as well as category they should belong to. Namespaces

are logical grouping of types for the purpose of identification. The System Namespaces is the

root for types in the .NET Framework. In .Net languages every program is created with a default Namespaces. Programmers can also

create their own Namespaces in .Net languages

In C# programming the class need not be same as the file name. Here is a basic C# program:

using System; ---------------------------------------------------------→ Importing a Namespace

//This program illustrates C# basic syntax ----------------------------→ Comments

public class SimpleProgram ----------------------------→ Class Wrapper {

static void Main()syntax ----------------------------→ Main method

{ Console.WriteLine("Hello"); }

}

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 5

Using is a C# keyword, which is a reserved word, which have special meaning a in a language

and therefore cannot be used by programmers as the names of variable, functions or any of the

other C# building blocks

A namespace is a logical grouping of predefined C# programming element. “using System;”

statement – is required to compile and run the program properly.

// - to comment just to the end of line i.e. single line comment /* this is a multi line or block comment */

“Class Wrapper” – A class declaration in C# is composed of attributes, modifiers, the class name

and a body. The body contains class members that can include constants, variables, methods,

properties, events, operators.

“Main Method” – it serves as the entry point for a C# program. When the program executable is

invoked, the system will call the Main method to launch the application.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 6

Solutions

1. Write a Program in C# to Check whether a number is Palindrome or not.

The Console Class provides access to the standard input, standard output, and standard error

streams. Standard input – is associated with the keyboard- anything that the user types on the

keyboard can be read from the standard input stream. Console.Read Method – reads the next character from the keyboard. It returns the int value -1 if

there is no more input available. Otherwise it returns as int representing the character read.

Console.ReadLine Method - reads all characters up to the end of the input line. The input is

returned as a string of characters.

Standard output – is usually directed to the screen, as is the standard error stream. Console.Write Method – writes text to the console without a carriage return Console.WriteLine Method – writes a text string including a carriage return to the out console

Program: using System;

class palindrome {

public static void Main() { int num=0,rev,num1=0,num2=0; Console.WriteLine( “To Check if the number is a Palindrome or not”); Console.WriteLine("Enter a number: ");

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

num2=num;

while(num>0) { rev=num%10; num=num/10; num1=num1*10+rev;

} if(num1==num2) Console.WriteLine("Entered number is a Palindrome.");

else

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 7

Console.WriteLine("Entered number is NOT a Palindrome."); } }

Test Data:

To Check if the number is a Palindrome or not Enter a number: 32123 Entered number is a Palindrome.

To Check if the number is a Palindrome or not

Enter a number: 532123

Entered number is NOT a Palindrome.

2. Write a Program in C# to demonstrate Command line arguments processing.

Basically main method can have two Signatures.

static void Main(string[] args)

or

static int Main(string[] args)

In which string[] args will store whatever is passed through command line to the application. We

can process all the elements passed into command Line by simply processing the array

string[] args. The parameter of the Main method is a string array that represents the command-

line arguments. To check for the existence of the arguments can, it be done by testing the length

property. We can access Command Line Arguments globally Using Environment Class's

GetCommandLineArguments() method which returns string[] array of all CommandLine

Arguments. So one can use command line arguments passed to Main function any were in

Program without passing it any were.

Program: using System;

class cmdarg

{ public static void Main(String[] args) { int num=0; for(int i=0;i<args.Length;i++)

num=num+int.Parse(argst[i]); Console.WriteLine("Sum of the given command line arguments is : "+ num); } }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 8

Command line arguments (1 2 3 4 5) are fed in the properties of the program.

Test Data:

Click on 'Run-> Run with-> Custom Parameters-> Enter 1 2 3 4 5

Sum of the given command line arguments is: 15

3. Write a Program in C# to find the roots of Quadratic Equation.

Program:

using System;

public class roots

{ double a=0, b=0, c=0, d=0, r1=0, r2=0, n=0, m=0; public void input()

{ Console.WriteLine("To find the roots of a quadratic equation, Enter a,b,c");

a = double.Parse(Console.ReadLine()); b = double.Parse(Console.ReadLine());

c = double.Parse(Console.ReadLine()); d = Math.Sqrt(b * b - 4 * a * c); if (d == 0)

{ Console.WriteLine("The Roots for the given Equation are Real and Equal");

r1 = r2 = -b / (2 * a); Console.WriteLine("Root is: " + r1 + "and" + r2); }

else if (d < 0) { Console.WriteLine("Roots for the given equation are Real and distinct"); r1 = (-b + d) / (2 * a);

r2 = (-b - d) / (2 * a); Console.WriteLine("The Roots are: " + (int)r1 + "and" + (int)r2); } else {

Console.WriteLine("The Roots for the given Equation are Imaginary"); n = -b / (2 * a); m = Math.Sqrt(Math.Abs(b * b - 4 * a * c)) / (2 * a); Console.WriteLine("Root 1: " + n + "+i " + m);

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 9

Console.WriteLine("Root 2: " + n + "-i " + m); } }

} class Quad { public static void Main() {

roots r = new roots(); r.input(); }

}

Test Data:

Enter a,b,c : a = 1 b = -2 c = -2 Equation has two roots. The roots are: root1 = 2.732051 root2 = -0.7320508

4. Write a Program in C# to demonstrate boxing and unBoxing.

Boxing

It is defined as the process of explicitly converting a value type into a corresponding reference

type by storing the variable in a System.Object.

Consider an example a variable of type short:

short s = 25;

If, during the course of your application, you wish to represent this value type as a reference

type, you would “box” the value as follows:

// Box the value into an object reference.

object objShort = s;

When you box a value, the CLR allocates a new object on the heap and copies the value type’s

value (in this case, 25) into that instance. What is returned to you is a reference to the newly

allocated object.

1. UnBoxing

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 10

It is the process of converting the value held in the object reference back into a corresponding

value type on the stack. The unboxing operation begins by verifying that the receiving data type

is equivalent to the boxed type, and if so, it copies the value back into a local stack-based

variable.

The following unboxing operation works successfully, given that the underlying type of the

objShort is indeed a short.

// Unbox the reference back into a corresponding short.

short anotherShort = (short)objShort;

Program:

using System; class Program

{ static void Main(String[] args)

{ Object o; Console.WriteLine(“Reading integer value int an object (boxing)”);

Console.WriteLine(“Enter an integer value:”); o=int.Parse(Console.ReadLine());

int i =(int)o; Console.WriteLine(“Boxed value:o=”+o);

Console.WriteLine(“Unboxing value of object into integer i: i=”+i);

Console.WriteLine(“Reading string into an object (boxing)”); Console.WriteLine(“Enter a string:”); o=Console.ReadLine();

string str =(String)o; Console.WriteLine(“Boxed value:o=”+o); Console.WriteLine(“Unboxing value of object into integer str: str=”+str); } }

Test Data:

Reading integer value int an object (boxing)

Enter an integer value: 1234

Boxed value:o= 1234 Unboxing value of object into integer i: i= 1234

Reading string into an object (boxing)

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 11

Enter a string: Hello Unboxing value of object into integer str: str= Hello

5. Write a Program in C# to implement Stack operations.

Stack operation: .NET includes a Stack class inside the System.Collections namespace. It is efficient because it is

implemented using a System.Collections.ArrayList, so if you need to consume a stack, it is a

better idea to use the built in .NET stack class. A stack is a data structure that allows to add and remove objects at the same position. The last object placed on the stack is the first one to be removed following a Last In First Out (LIFO)

data storing method. Common functions include Push and Pop etc.

Program:

using System;

class stack {

int top; int[] s; public stack(int size)

{ s = new int[size];

top = -1; } public stack() { } public void pop() {

if (top == -1) {

Console.WriteLine("No elements to Pop\n"); return; } Console.WriteLine("The Poped element is" + s[top]); top--;

} public void push(int var) {

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 12

//Console.WriteLine("top = " + top); s[++top] = var; }

public void display() { Console.WriteLine("The Contents of the Stack are\n"); if (top == -1) {

Console.WriteLine("No elements to Display\n"); return; }

for (int i = 0; i<=top; i++) Console.WriteLine(s[i]); }

}

public class demo {

public static void Main() { Console.WriteLine("Enter the Size of Stack\n");

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

stack st = new stack(size); int eflag = 0; do

{ Console.WriteLine("\n\nEnter your Choice\n");

Console.WriteLine("1. Push"); Console.WriteLine("2. Pop"); Console.WriteLine("3. Display");

Console.WriteLine("4. Exit\n\n"); int ch = int.Parse(Console.ReadLine()); switch (ch)

{

case 1: Console.WriteLine("Enter a Number to Push\n"); int var = int.Parse(Console.ReadLine()); st.push(var);

break; case 2: st.pop(); break; case 3: st.display(); break; case 4: eflag=1; break;

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 13

} } while (eflag==0); }

}

Test Data:

Enter the size of the stack: 3 Enter your choice:

1. Push

2. Pop

3. Display 4. Exit 1 Enter a number to push: 1

Enter your choice: 1. Push

2. Pop 3. Display 4. Exit

1 Enter a number to push: 2

Enter your choice: 1. Push

2. Pop 3. Display 4. Exit

3 The contents of the stack are:

1 2

6. Write a program to demonstrate Operator overloading.

Operator overloading, also known as overloading, provides a way to define and use operators

such as +, -, and / for user-defined classes or structs. It allows us to define/redefine the way

operators work with our classes and structs. This allows programmers to make their custom types

look and feel like simple types such as int and string. It consists of nothing more than a method

declared by the keyword operator and followed by an operator. There are three types of

overloadable operators called unary, binary, and conversion. Not all operators of each type can

be overloaded. Overloading Unary Operators: They include +, -, !, ~, ++, --, true, and false.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 14

Overloading Binary Operator : Binary operators are those that require two operands/parameters

for the operation. One of the parameters has to be of a type in which the operator is declared.

They include

+, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, and <=. Overloading Conversion Operator: Conversion operators are those that involve converting from

one data type to another through assignment. There are implicit and explicit conversions. · Implicit conversions are those that involve direct assignment of one type to another. · Explicit conversions are conversions that require one type to be casted as another type in order

to perform the conversion. Conversions that may cause exceptions or result in loss of data as the

type is converted should be handled as explicit conversions.

Program:

using System;

namespace Ex6 { class Complex

{ public double real;

public double imag; public Complex(double a, double b) {

real=a;

imag=b; } public Complex()

{ }

public static Complex operator+(Complex C1, Complex C2) {

Complex C3 = new Complex(C1.real+C2.real,C1.imag+C2.imag); return C3;

}

public static Complex operator-(Complex C1, Complex C2) { Complex C3 = new Complex(C1.real-C2.real,C1.imag-C2.imag); return C3; }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 15

public override string ToString () { string s;

if(imag>0) s=real.ToString()+"+"+imag.ToString()+"i";

else s=real.ToString()+"-"+Math.Abs(imag).ToString()+"i"; return s;

} }

class MainClass

{ public static void Main (string[] args) {

Complex C1=new Complex(10,20);

Complex C2=new Complex(5,10); Complex C3=C1+C2;

Complex C4=C1-C2; Console.WriteLine("C1:" +C1.ToString()+"\nC2:

"+C2.ToString()+"\nC3=C1+C2: "+C3.ToString()+"\nC4=C1-C2: "+C4.ToString());

} }

}

Test Data:

C1=10+20i

C2=5+10i

C3=C1+C2=15+30i

C4=C1-C2=5+10i

7. Write a Program in C# to find the second largest element in a single dimensional array.

An array is a data structure that contains a number of variables of the same type. Arrays are

declared with a data type: Data type [ ] arrayName;

The properties of an array:

● An array can be Single-Dimensional, Multidimensional. ● C# also supports two varieties of multidimensional arrays.

● Rectangular array: each row will be of the same length

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 16

● Jagged array: each row will vary in length ● The default value of numeric array elements are set to zero, and reference elements are set to

null.

● A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

● An array with n elements is indexed from 0 to n-1. ● Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable, you can use foreach iteration on all arrays in C#.

Single-Dimensional Arrays:

int[] array = new int[5];

This array contains the elements from array[0] to array[4]. The new operator is used to create the

array and initialize the array elements to their default values. In this example, all the array

elements are initialized to zero.

Eg. string[] stringArray = new string[6];

It is possible to initialize an array upon declaration, in which case, the rank specifier is not

needed because it is already supplied by the number of elements in the initialization list.

For example:

int[] array1 = new int[5] { 1, 3, 5, 7, 9 };

A string array can be initialized in the same way

Multidimensional Arrays:

Arrays can have more than one dimension. Here is an example of two dimensional

array of four rows and two columns:

int[,] array = new int[4, 2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[, ,] array1 = new int[4, 2, 3];

Can initialize the array

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

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

Program:

using System; class SLar { int size; int[] nums; int lar, sec;

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 17

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())); }

}

Test Data:

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 18

Enter the Size of Array: Enter the elements of Array: 7

4 5 Second Largest number: 5

8. Write a Program in C# to multiply to matrices using Rectangular arrays.

Program:

using System; class MatMulti

{ int r1,r2,c1,c2;

double[,]a; double[,]b; double[,]c; public MatMulti(int r1,int c1,int r2,int c2) {

a=new double[(this.r1=r1),(this.c1=c1)]; b=new double[(this.r2=r2),(this.c2=c2)];

c=new double[r1,c2]; } public void Multiply() { if(c1==r2)

{ Console.WriteLine("Enter elements of first matrix");

for(int i=0;i<r1;i++) for(int j=0;j<c1;j++) a[i,j]=double.Parse(Console.ReadLine());

Console.WriteLine("Enter elements of second matrix"); for(int i=0;i<r2;i++)

for(int j=0;j<c2;j++) b[i,j]=double.Parse(Console.ReadLine());

for(int i=0;i<r1;i++) { for(int j=0;j<c2;j++) { c[i,j]=0;

for(int k=0;k<r2;k++) c[i,j]+=a[i,k]*b[k,j]; }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 19

}

Console.WriteLine("First matrix"); for(int i=0;i<r1;i++)

{ for(int j=0;j<c1;j++) Console.Write(a[i,j]+" "); Console.WriteLine(); }

Console.WriteLine("Second matrix");

for(int i=0;i<r2;i++) {

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

Console.Write(b[i,j]+" "); Console.WriteLine(); }

Console.WriteLine("Product matrix is:"); for(int i=0;i<r1;i++)

{ for(int j=0;j<c2;j++) Console.Write(c[i,j]+" "); Console.WriteLine(); }

} else

Console.WriteLine("Multiplication is not possible:"); } } class MultiImpl

{ public static void Main() { int a,b,c,d; Console.WriteLine("Enter no.of rows and columns of first matrix:");

a=int.Parse(Console.ReadLine()); b=int.Parse(Console.ReadLine());

Console.WriteLine("Enter no.of rows and columns of second matrix:"); c=int.Parse(Console.ReadLine()); d=int.Parse(Console.ReadLine()); MatMulti m=new MatMulti(a,b,c,d); m.Multiply(); } }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 20

Test Data:

Enter no.of rows and columns of first matrix: 1. 3

Enter elements of first matrix:

1 2 3 1 2 3 Enter no.of rows and columns of first matrix: 3 2

Enter elements of second matrix: 2 1

1 2 1 1

Product matrix is: 1. 8 7 8

9. Find the sum of all the elements present in a jagged array of 3 inner arrays.

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of

different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

The following is a declaration of a single-dimensional array that has three elements, each of

which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before using jaggedArray, its elements must be initialized.

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[4];

jaggedArray[2] = new int[2];

Each of the elements is a single-dimensional array of integers. The first element is an array of 5

integers, the second is an array of 4 integers, and the third is an array of 2 integers. It is also

possible to use initializers to fill the array elements with values, in which case the array size is

not needed. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };

jaggedArray[1] = new int[] { 0, 2, 4, 6 };

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 21

jaggedArray[2] = new int[] { 11, 22 };

This way also the array can be initialized:

int[][] jaggedArray2 = new int[][]

{

new int[] {1,3,5,7,9},

new int[] {0,2,4,6},

new int[] {11,22}

};

Program:

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 " + arr[i].Length + " : ");

for (int j = 0; j < arr[i].Length; j++) { arr[i][j] = int.Parse(Console.ReadLine()); sum += arr[i][j];

} } Console.WriteLine("The Sum is = " + sum);

} }

Test Data:

Enter the size of the Inner Array1:

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 22

2 Enter elements for inner Array 1: 1

1

Enter the size of the Inner Array2: 1 Enter elements for inner Array 2: 1

Enter the size of the Inner Array3: 1

Enter elements for inner Array 3:

1 The sum is: 4

10. Write a program to reverse a given string using C#.

The string type represents a string of Unicode characters. string is an alias for System.String in

the .NET Framework.

The String object is immutable. Every time any use of the methods in the System.String class,

we create a new string object in memory, which requires a new allocation of space for that new

object. In situations where you need to perform repeated modifications to a string, the overhead

associated with creating a new String object can be costly. The System.Text.String Builder class

can be used when you want to modify a string without creating a new object. For example, using

the StringBuilder class can boost performance when concatenating many strings together in a

loop.

Program:

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

namespace RevStr { public class StrRev {

string str1, str2; public StrRev(string s) { str1 = s; }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 23

public string Reverse() { for (int i = str1.Length; i > 0; i--)

{ string s = str1.Substring(i - 1, 1); str2 = str2 + s; } str2 = str2 + "\n";

return str2; } }

public class Program { public static void Main(string[] args)

{ string s1, s2; Console.WriteLine("Enter a string : ");

s1 = Console.ReadLine(); StrRev sr = new StrRev(s1);

s2 = sr.Reverse(); Console.WriteLine("The reverse is : \n" + s2); Console.ReadLine();

}

} }

Test Data:

Enter a string: Hello

The reverse is: olleH

11. Using Try, Catch and Finally blocks write a program in C# to demonstrate error

handling.

The .NET platform provides a standard technique to send and trap runtime errors: structured

exception handling (SEH). Developers now have a unified approach to error handling, which is

common to all languages targeting the .NET universe. The syntax used to throw and catch

exceptions across assemblies and machine boundaries is identical. Another bonus of .NET

exceptions is the fact that rather than receiving a cryptic numerical value that identifies the

problem at hand, exceptions are objects that contain a human-readable description of the

problem, as well as a detailed snapshot of the call stack that triggered the exception in the first

place. This involves the use of four interrelated entities: • A class type that represents the details of the exception that occurred

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 24

• A member that throws an instance of the exception class to the caller • A block of code on the caller’s side that invokes the exception-prone member • A block of code on the caller’s side that will process (or catch) the exception should it occur

Program:

using System; class Program { public static void Main()

{ try

{

int a = 10 b = 0, c; c = a / b; Console.WriteLine(“C=a/b=”,c);

} catch (DivideByZeroException dbze) {

Console.WriteLine("Division by zero!" ); }

Try { String s =”Malayalam”);

String s1=s+s[11];

} catch (IndexOutOfRangeException iore) {

Console.WriteLine("Array Index out of range”); }

finally { Console.WriteLine("Exception handling has been demonstrated"); } }

}

Test Data:

Division by zero! Array Index out of range Exception handling has been demonstrated

12. Design a simple calculator using Switch Statement in C#.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 25

Program:

using System;

namespace SimpleCalc

{ enum Choice { Add = 1, Subtract,

Multiply, Divide,

Read, Exit

}

class SimpleCalculator {

Double a, b, ans; Choice ch;

public void read() {

Console.WriteLine(“Enter value of a:“); a=double.Parse(Console.ReadLine()); Console.Write(“b: “);

b=double.Parse(Console.ReadLine()); }

public void displayMenu() { Console.WriteLine(“ 1. a + b \n2. a – b \n3.a* b \n4. a/b\n5. Re-enter values of a & b

\n6.Exit \n Your choice: “);

}

public void loop() {

While(ch!=Choice.Exit) { displayMenu(); ch = (Choice)int.Parse(Console.ReadLine()); switch (op)

{ case Choice.Add; ans = a+ b;

Console.WriteLine(“ans=” +ans);

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 26

break; case Choice.Subtract; ans = a- b;

Console.WriteLine(“ans=” +ans); break; case Choice.Multiply; ans = a* b; Console.WriteLine(“ans=” +ans);

break; case Choice.Divide; if(b!=0) {

ans = a/ b; Console.WriteLine(“ans=” +ans); }

Else { Console.WriteLine(“b = 0, division by zero!”);

} break;

case Choice.Read; read(); break;

case Choice.Exit;

break; default: Console.WriteLine(“Invalid Choice”);

break;

}

} } } public class Program

{

public static void Main(string[] args) { SimpleCalculator sc = new SimpleCalculator();

sc.read(); sc.loop(); } }

Test Data:

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 27

Enter value of a: 8

Enter value pf b: 2

1. a + b

2. a – b 3. a * b 4. a / b 5. Re-enter values a & b 6. Exit

Your choice: 1 Ans: 10

1. a + b

2. a – b

3. a * b 4. a / b

5. Re-enter values a & b 6. Exit

Your choice: 9

Invalid choice

13. Demonstrate Use of Virtual and override key words in C# with a simple Program

Overrriding method is basically run time polymorphism in C#. When a subclass contains a

method with the same name and signature as in the supper class then it is called as method

overriding.

Virtual method is a method in a base class which the child class can reuse it or redefine and

customize its behavior to be appropriate to its functionality. The virtual keyword is used to

modify a method, property, indexer or event declaration, and allow it to be overridden in a

derived class. For example, this method can be overridden by any class that inherits it:

public virtual double Area()

{ return x * y; }

· The implementation of a virtual member can be changed by an overriding member in a derived

class. · When a virtual method is invoked, the run-time type of the object is checked for an overriding

member. · The overriding member in the most derived class is called, which might be the original

member, if no derived class has overridden the member. · By default, methods are non-virtual. One cannot override a non-virtual method. · You cannot use the virtual modifier with the static, abstract, private or override modifiers.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 28

· A virtual inherited property can be overridden in a derived class by including a property

declaration that uses the override modifier.

The override modifier is required to extend or modify the abstract or virtual implementation of

an inherited method, property, indexer, or event. · An override method provides a new implementation of a member inherited from a base class. · The method overridden by an override declaration is known as the overridden base method. · The overridden base method must have the same signature as the override method.

Program:

using System; using System.Collections.Generic;

using System.Linq; using System.Text;

namespace Virtualnride

{ class A {

Private int x; Public A(int X) {x=X;}

Public virtual void display(){ Console.WriteLine(“x =”+x);

} }

class B : A { Private int y;

Public B(intX, int Y):base(X) {y=Y;} Public override void display(){ Base.display();

Console.WriteLine(“y=”+y); }

}

class Program { static void Main(string[] args) { A obj =new A(10);

A obj =new B(10,20); Console.WriteLine(“For object of type class A:”); obj.display();

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 29

Console.WriteLine(“For object of type class B:”); obj1.display(); }

}

Test Data: For object of type class A: x=10

For object of type class A:

x=10 y=20

14. Implement linked lists in C# using the existing collections name space.

A linked list is an array of objects that however, is quite different from a simple array. A regular

array allocates a specific part of the memory automatically. Here a linked list has two values –

one with the stored data and one referencing the next value. These two fields together build a

node, that is – a unit inside the linked list.

Values aren’t stored in any particular order, however the reference to the next value helps finding

and inserting the needed values much easier.

The System.Collections namespace contains interfaces and classes that define various collections

of objects, such as lists, queues, bit arrays, hash tables and dictionaries.

Program:

using System; using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Collections;

namespace LinkedList {

public class MyLinked { private ArrayList arr; public MyLinked() {

Console.WriteLine("Linked list created"); arr = new ArrayList(0); } public void insert(int value, int pos)

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 30

{ if (checkpos(pos)) arr.Insert(pos, value);

} public void add(int val) { arr.Add(val); }

public Boolean checkpos(int pos) { if (arr.Count < pos || pos < 0)

{ Console.WriteLine("position should be greater than 0 and in between 1 & " +

arr.Count);

return false; } else

return true; }

public Boolean checkLen() { if (arr.Count == 0)

{

Console.WriteLine("list empty"); return false; }

return true; }

public void remove(int pos) { if (pos >= 0 && pos < arr.Count) {

arr.RemoveAt(pos); } else

{ Console.WriteLine("Position is out of array size"); } }

public void delete(int val) { if (arr.IndexOf(val) >= 0 && arr.IndexOf(val) < arr.Count) arr.Remove(val); else Console.WriteLine("The element does not present");

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 31

} public void show() {

int[] a = new int[arr.Count]; arr.CopyTo(a); if (checkLen()) foreach (int i in arr) Console.WriteLine(i);

} public void clearAll() {

arr.Clear(); } }

public class Demo { public static void Main()

{ MyLinked l = new MyLinked();

int pos, val; while (true) {

Console.Write("\n\n1. Add \n2. Insert\n3. Delete By Position \n4. Delete By Value\n5.

Display \n6. Clear \n7. Exit \nEnter your choice : "); String ch = Console.ReadLine(); switch (ch)

{ case "1":

Console.WriteLine("Enter the value : "); val = int.Parse(Console.ReadLine()); l.add(val); break;

case "2": Console.WriteLine("Enter the value and position "); val = int.Parse(Console.ReadLine());

pos = int.Parse(Console.ReadLine()); l.insert(val, pos - 1); break; case "3":

if (l.checkLen()) { Console.WriteLine("Enter the position "); pos = int.Parse(Console.ReadLine()); l.remove(pos - 1); }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 32

break; case "4": if (l.checkLen())

{ Console.WriteLine("Enter the value"); val = int.Parse(Console.ReadLine()); l.delete(val); }

break; case "5": l.show();

break; case "6": l.clearAll();

break; case "7": Environment.Exit(0);

break; default: break;

} } }

}

}

Test Data: 1. Add

2. Insert

3. Delete By Position

4. Delete By Value

5. Display

6. Clear

7. Exit

Enter your choice : 1

5

15. Write a program to demonstrate abstract class and abstract methods in C#.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 33

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like

to make classes that only represent base classes, and don’t want anyone to create objects of these

class types. Here we make use of abstract classes to implement such functionality in C# using the

modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations

of this. An abstract class can contain either abstract or non-abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

Program:

using System;

namespace Abstract

{ public abstract class Add {

public abstract void readandadd(); public abstract void display();

}

public class BinAdd : Add {

Private double a,b,c;

public override void readandadd() { Console.WriteLind(“Enter value of a:”);

a=double.Parse(Console.ReadLine()); Console.WriteLind(“Enter value of b:”);

b=double.Parse(Console.ReadLine()); c=a + b; }

public override void display()

{ Console.WriteLine("Value of a ({0})+ b({1}) = c {2}”, a, b, c);

} } public class Program { public static void Main(string[] args)

{ BinAdd b = new BinAdd(); b.readamdadd(); b.display(); }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 34

}

Test data:

Enter the value of a:

4 Enter the value of b: 3 Value of a (4) + b (3) = 7

16. Write a program in C# to build a class which implements an interface which already

exists.

Interface is a reference type and it contains only abstract members. Has only signature. Can

implement any number of interfaces in a single derived class. An interface can inherit multiple

inheritances. Few existing interfaces are ICloneable, IComparable, etc

∙ Interfaces describe a group of related functionalities that can belong to any class or struct.

· When a class or struct is said to inherit an interface, it means that the class or struct provides an

mplementation for all of the members defined by the interface. · Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a

base class or struct, with two exceptions: 1. A class or struct can inherit more than one interface.

2. When a class or struct inherits an interface, it inherits only the method names and signatures,

because the interface itself contains no implementations.

· An interface contains only the signatures of methods, delegates or events. · The implementation of the methods is done in the class that implements the interface. · An interface cannot contain fields.

· Interfaces members are automatically public.

Program:

using System;

class mycloneable : ICloneable

{ int data1; String data2;

public mycloneable(int a, String s)

{ data1 = a; data2 = s;

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 35

} public mycloneable() : this(0,” “) { } public override Sting ToString()

{ String str = “data1: “ +data1 + “ data2 : ””+data2 ; Return str; }

public mycloneable clone()

{ return new mycloneable(data1, data2);

}

object ICloneable.Clone()

{ return clone(); }

}

class Program

{ public static void Main(String[] args) { mycloneable mc1 = new mycloneable(10, "Object1"); mycloneable mc2 = (mycloneable)mc1.clone();

Console.WriteLine("mc1: “+mc1 +”\nmc2 : “ + mc2);

}

}

Test data:

mc1: data1: 10 data2: Object1

mc2: data1: 10 data2: Object1

17. Write a program to illustrate the use of different properties in C#.

In contrast to traditional accessor and mutator methods, .NET languages prefer to enforce

encapsulation using properties, which simulate publicly accessible points of data. Rather than

requiring the user to call two different methods to get and set the state data, the user is able to

call what appears to be a public field. A C# property is composed using a get block (accessor)

and set block (mutator).

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 36

Properties enable a class to expose a public way of getting and setting values, while hiding

implementation or verification code. The get property accessor is used to return the property

value, and a set accessor is used to assign a new value. These accessors can have different access

levels. The value keyword is used to define the value being assigned by the set indexer. · Properties that do not implement a set method are read only. · The code block for the get accessor is executed when the property is read; the code block for

the set accessor is executed when the property is assigned a new value. · A property without a set accessor is considered read-only. A property without a get accessor is

considered write-only. A property with both accessors is read-write.

Program:

using System;

class student

{ private String usn; private String Name;

private double perc; private bool validated;

private static String collegeName=”RVCE”; public Student(String USN) {usn = USN;} public static String CollegeName { get { return collegeName; }}

public String USN {

get { return usn; } }

public string Name { get { return name ; } set { name = value; } }

public double percentage {

get { return perc; } set { perc = value; } } public bool validated { set { validated = value; }

} } }

class Program

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 37

{ public static void Main(String[] args) {

Student s = new student("1RV07MCA47"); s.name = "Ram"; s.percentage = 79.0; s.validated()=true; Consolidated.WriteLine(“After using accessors and mutators:”);

Consolidated.WriteLine(“College name: {0}”,Student.CollegeName); Consolidated.WriteLine(“USN : {0}”,s.USN); Consolidated.WriteLine(“Name : {0}”,s.Name);

Consolidated.WriteLine(“Percentage : {0}”,s.Percentage);

} }

Test data:

After using accessors and mutators:

College name: RVCE USN : 1RV07MCA47 Name : Ram

Percentage : 79.0

18. Demonstrate arrays of interface types with a C# program.

using System;

namespace InterfaceArray {

public interface IShape { void Calculate(); void Display(); }

public class Rectangle : IShape {

private double Area; private double Length; private double Breadth; public Rectangle(double l, double b) {

this.Length = l; this.Breadth = b; }

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 38

public void Calculate() { Area = Length * Breadth;

} public void Display() { Console.WriteLine("Area of Rectangle is : " + Area); }

}

public class Circle : IShape

{

private double Area; private double Radius; public Circle(double s)

{ Radius = s; }

public void Calculate() {

Area = 3.1416 * Radius * Radius; } public void Display()

{

Console.WriteLine("Area of Circle is : " + Area); } }

public class Program {

public static void Main(string[] args) { IShape[] s = { new Rectangle(10, 20), new Circle(40) }; foreach (IShap s om omtfArray) {

s.Calculate();

s.Display();

} Console.ReadLine(); } } }

Test data:

Area of a Rectangle:200

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 39

Area of a Circle: 5033.6

Viva questions

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 40

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 41

VIVA- QUESTIONS

Ques. No. Viva Questions

1 What is boxing and Unboxing feature in C#?

2 State the difference between value types and reference types

3 What is an object?

4 What is a class?

5 What is a namespace?

6 Explain some of the important features of Visual studio

7 Explain the anatomy of a basic C# class

8 What is a constructor overloading

9 What are the basic input and output console class?

10 What is reference type? Give examples

11 List the different iteration constructs used in C#

12 List the different control flow constructs used in C#

13 Explain a jagged array

14 Mention the difference between the rectangular array and jagged array

15 What is the difference between for loop and while loop?

16 What is enumeration? Give Example

17 What is a value type? Give examples

18 What are the different functions of array object?

19 What the different function and properties of string object?

20 What is encapsulation

21 What is ReadOnly Field

22 Explain casting

23 What is polymorphism? Explain with an example

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 42

24 Which are the 3 pillars of OOPs

25 What is an exception

26 What is debugging?

27 What is an error?

28 What are the different types of Exceptions thrown in .Net

29 Explain Garbage collection in .Net

30 Explain the base class System.Exception

31 What is the difference between Final and Finally

32 What is interfaces?

33 What is the difference between and interface and abstract class

34 Explain IEnumeration

35 Explain IConvertible

36 Explain ICloneable

37 Explain Icomparable

38 What are the built in interfaces

39 What is a metadata?

40 What is call backs, give example

41 Describe overloading

42 What is Delegate?

43 What is events?

44 What are the different types of Delegates?

45 What is indexers?

46 Explain checked and unchecked keyword in C#

47 What is operator overloading?

48 What is an array?

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 43

49 Give few String methods and explain

50 Explain ‘foreach’ loop

2. Extra Programs

1. Write a program to validate the username and password. Give corresponding messages

(Connect to the DB to validate the username and password).

2. Write a program to find the perimeter, area of a triangle(when 3 sides are given) and square

using concepts of virtual and override methods in C#

3. Use windows forms and design a login page. And implement the prg1.

.Net Lab Cycle For the V semester

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 44

Subject Code: 10MCA57 I.A Marks: 50

Hours/Week: 3 Exam Hours: 03

Total Hours: 42 Exam Marks: 50

Lab

Cycle Prg Nos.

Program number with the question

1

1.

2. 1 Write a Program in C# to check whether a number is Palindrome or not.

2

3.

4. 2

3

Write a Program in C# to demonstrate Command line arguments processing.

Write a Program in C# to find the roots of Quadratic Equation.

3

4

5

Write a Program in C# to demonstrate Boxing and unBoxing

Write a Program in C# to implement Stack operations.

4

6

7

Write a Program to demonstrate Operator overloading.

Write a Program in C# to find the second largest element in a single dimensional array.

5

8

9

Write a Program in C# to multiply to matrices using Rectangular arrays.

Find the sum of all the elements present in a jagged array of 3 inner arrays.

6

10

11

Write a Program to reverse a given string using C#.

Using Try, Catch and Finally blocks write a program in C# to demonstrate error handling.

7

12

13

Design a simple calculator using Switch Statement in C#.

Demonstrate Use Of Virtual and override keyword in C# with a simple Program.

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 45

8

14

15

Implement Linked Lists in C# using the existing collections name space.

Write a Program to demonstrate abstract class and abstract methods in C#.

9

16

17

Write a Program in C# to build a class which implements an interface which already exists.

Write a Program to illustrate the use of different properties in C#.

10

18 Demonstrate arrays of interface types with a C# program.

11

5. Any backlogs

DotNet Laboratory Eduoncloud.com MCA 5th Semester

Dept of RVCE MCA Page 46