Csharp Lab Manual
Csharp Lab Manual
LABORATORY MANUAL
C# PROGRAMMING
21CSL582/ 21CBL584
V Semester
Prepared by:
1. Mrs. Bharathi K
2. Mr. Vinayak
3. Mrs. Deeksha Satish
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(Accredited by NBA)
ACHARYA INSTITUTE OF TECHNOLOGY
MOTTO
"Nurturing Aspirations Supporting Growth" VISION “Acharya Institute of Technology, committed to the
cause of sustainable value-based education in all disciplines, envisions itself as a global fountainhead of
innovative human enterprise, with inspirational initiatives for Academic Excellence”.
MISSION OF INSTITUTE
“Acharya Institute of Technology strives to provide excellent academic ambiance to the students for
achieving global standards of technical education, foster intellectual and personal development,
meaningful research and ethical service to sustainable societal needs.”
PSO-1 Students shall apply the knowledge of hardware, system software, algorithms, computer
networks and data bases for real world problems.
PSO-2 Students shall design, analyze and develop efficient and secure algorithms using appropriate
data structures, databases for processing of data.
PSO-3 Students shall be capable of developing stand alone, embedded and web-based solutions having
easy to operate interface using software engineering practices and contemporary computer
programming languages.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, societal, and environmental considerations.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
switch (symbol)
{
case "+":
res = num1 + num2;
Console.WriteLine("Addition:" + res);
break;
case "-":
Acharya Institute of Technology – Department of CS&E C# .NET Page 8
res = num1 - num2;
Console.WriteLine("Subtraction:" + res);
break;
case "*":
res = num1 * num2;
Console.WriteLine("Multiplication:" + res);
break;
case "/":
res = num1 / num2;
Console.WriteLine("Division:" + res);
break;
case "%":
res = num1 % num2;
Console.WriteLine("Remainder:" + res);
break;
default:
Console.WriteLine("Wrong input");
break;
}
Console.ReadLine();
Console.Write("Do you want to continue(y/n):");
value = Console.ReadLine();
}
catch(Exception e)
{
Console.Write(e.Message);
}
}
}
}
Acharya Institute of Technology – Department of CS&E C# .NET Page 9
Output:
using System;
class ArmstrongNumbers
{
// Function to calculate the number of digits in a number
static int CountDigits(int num)
{
int count = 0;
while (num > 0)
{
num /= 10;
count++;
}
return count;
}
2. Develop a C# program to list all substrings in a given string. [ Hint: use of Substring() method]
using System;
Console.WriteLine("Enter a string:");
string inputString = Console.ReadLine();
ListSubstrings(inputString);
Console.ReadLine();
using System;
class Program : System.Exception {
static void Main(string[] args)
{
// Declare an array of max index 4
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("\n\nDeclared array size:"+ arr.Length);
Console.WriteLine("\n\nEnter n1");
int n1= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter n2");
int n2= Convert.ToInt32(Console.ReadLine());
try{
Console.WriteLine(n1/n2);
}
catch (DivideByZeroException e)
{
Console.WriteLine("\t-----Executing divide by zero exception----");
Console.WriteLine(e.Message);
}
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
try {
Console.WriteLine(arr[100]);
}
catch (IndexOutOfRangeException e) {
5. Develop a C# program to generate and print Pascal Triangle using Two Dimensional arrays.
using System;
class PascalTriangle
{
public static void printPascal(int n)
{
int[,] arr = new int[n, n];
for (int line = 0; line < n; line++)
{
for (int i = 0; i <= line; i++)
{
Acharya Institute of Technology – Department of CS&E C# .NET Page 14
if (line == i || i == 0)
arr[line, i] = 1;
else
arr[line, i] = arr[line - 1, i - 1] +
arr[line - 1, i];
Console.Write(arr[line, i]);
}
Console.WriteLine("");
}
}
// Driver Code
public static void Main ()
{
int n = 5;
printPascal(n);
}
}
Output:
6. Develop a C# program to generate and print Floyds Triangle using Jagged arrays.
using System;
Acharya Institute of Technology – Department of CS&E C# .NET Page 15
class Program
{
static void Main()
{
Console.WriteLine("Enter the number of rows for Floyd's Triangle:");
if (!int.TryParse(Console.ReadLine(), out int rows) || rows <= 0)
{
Console.WriteLine("Please enter a valid positive number of rows.");
return;
}
int[][] floydsTriangle = GenerateFloydsTriangle(rows);
Console.WriteLine("Floyd's Triangle:");
// Print the generated Floyd's Triangle
for (int i = 0; i < rows; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write(floydsTriangle[i][j] + " ");
}
Console.WriteLine();
}
}
static int[][] GenerateFloydsTriangle(int rows)
{
int[][] triangle = new int[rows][];
int count = 1;
for (int i = 0; i < rows; i++)
{
triangle[i] = new int[i + 1];
for (int j = 0; j <= i; j++)
{
Acharya Institute of Technology – Department of CS&E C# .NET Page 16
triangle[i][j] = count;
count++;
}
}
return triangle;
}
}
OUTPUT:
Enter the number of rows for Floyd's Triangle:
3
Floyd's Triangle:
1
23
456
7. Develop a C# program to read a text file and copy the file contents to another text file.
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
Console.WriteLine("Enter the path of the source text file:");
Acharya Institute of Technology – Department of CS&E C# .NET Page 17
string sourceFilePath = Console.ReadLine();
// Check if the source file exists
if (!File.Exists(sourceFilePath))
{
Console.WriteLine("Source file does not exist.");
return;
}
Console.WriteLine("Enter the path of the destination text file:");
string destinationFilePath = Console.ReadLine();
// Read the contents of the source file
string fileContents = File.ReadAllText(sourceFilePath);
// Write the contents to the destination file
File.WriteAllText(destinationFilePath, fileContents);
Console.WriteLine("File contents copied successfully!");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
OUTPUT:
Enter the path of the source text file:
C:\Users\admin\OneDrive\Desktop\myproject6\a.txt
Enter the path of the destination text file:
C:\Users\admin\OneDrive\Desktop\myproject6\b.txt
File contents copied successfully!
8. Develop a C# Program to Implement Stack with Push and Pop Operations [Hint: Use class,
get/set properties, methods for push and pop and main method]
Acharya Institute of Technology – Department of CS&E C# .NET Page 18
using System;
public class Stack
{
private int[] stackArray;
private int top;
private int maxSize;
// Constructor to initialize the stack
public Stack(int size)
{
maxSize = size;
stackArray = new int[maxSize];
top = -1; // Stack is initially empty
}
// Push operation to add an element to the stack
public void Push(int item)
{
if (top == maxSize - 1)
{
Console.WriteLine("Stack Overflow! Cannot push element.");
return;
}
stackArray[++top] = item;
Console.WriteLine($"Pushed element: {item}");
}
// Pop operation to remove and return the top element from the stack
public int Pop()
{
if (top == -1)
{
Console.WriteLine("Stack Underflow! Stack is empty.");
Acharya Institute of Technology – Department of CS&E C# .NET Page 19
return -1; // Return a default value indicating stack underflow
}
int poppedItem = stackArray[top--];
Console.WriteLine($"Popped element: {poppedItem}");
return poppedItem;
}
// Property to check if the stack is empty
public bool IsEmpty
{
get { return (top == -1); }
}
}
class Program
{
static void Main(string[] args)
{
// Creating a stack of size 5
Stack myStack = new Stack(5);
// Pushing elements onto the stack
myStack.Push(10);
myStack.Push(20);
myStack.Push(30);
// Pop elements from the stack
myStack.Pop();
myStack.Pop();
myStack.Pop();
myStack.Pop(); // Trying to pop from an empty stack
Console.ReadLine(); // To keep the console window open
}
}
OUTPUT:
Acharya Institute of Technology – Department of CS&E C# .NET Page 20
Pushed element: 10
Pushed element: 20
Pushed element: 30
Popped element: 30
Popped element: 20
Popped element: 10
Stack Underflow! Stack is empty.
9. Design a class “Complex” with data members, constructor and method for overloading a binary
operator ‘+’. Develop a C# program to read Two complex number and Print the results of
addition.
using System;
public class Complex
{
private double real;
private double imaginary;
// Constructor to initialize complex numbers
public Complex(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Overloading the + operator for complex number addition
public static Complex operator +(Complex c1, Complex c2)
{
double newReal = c1.real + c2.real;
double newImaginary = c1.imaginary + c2.imaginary;
return new Complex(newReal, newImaginary);
}
// Method to display complex number
Acharya Institute of Technology – Department of CS&E C# .NET Page 21
public void DisplayComplexNumber()
{
Console.WriteLine($"({real} + {imaginary}i)");
}
}
class Program
{
static void Main(string[] args)
{
// Reading two complex numbers
Console.WriteLine("Enter the real part of the first complex number:");
double real1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the imaginary part of the first complex number:");
double imaginary1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the real part of the second complex number:");
double real2 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the imaginary part of the second complex number:");
double imaginary2 = double.Parse(Console.ReadLine());
// Creating Complex objects
Complex complex1 = new Complex(real1, imaginary1);
Complex complex2 = new Complex(real2, imaginary2);
// Adding complex numbers and displaying the result
Console.WriteLine("\nSum of the complex numbers:");
Complex result = complex1 + complex2;
result.DisplayComplexNumber();
Console.ReadLine(); // To keep the console window open
}
}
OUTPUT:
Enter the real part of the first complex number:
2
Acharya Institute of Technology – Department of CS&E C# .NET Page 22
Enter the imaginary part of the first complex number:
4
Enter the real part of the second complex number:
4
Enter the imaginary part of the second complex number:
1
Sum of the complex numbers:
(6 + 5i)
10. Develop a C# program to create a class named shape. Create three sub classes namely: circle,
triangle and square, each class has two member functions named draw () and erase (). Demonstrate
polymorphism concepts by developing suitable methods, defining member data and main program.
using System;
// Base Shape class
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing Shape");
}
public virtual void Erase()
{
Console.WriteLine("Erasing Shape");
}
}
// Circle subclass
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
// Triangle subclass
public class Triangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Triangle");
}
public override void Erase()
{
Console.WriteLine("Erasing Triangle");
}
}
// Square subclass
public class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Square");
}
public override void Erase()
{
Console.WriteLine("Erasing Square");
}
}
Acharya Institute of Technology – Department of CS&E C# .NET Page 24
class Program
{
static void Main(string[] args)
{
// Creating instances of each shape
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
// Demonstrating polymorphism
foreach (Shape shape in shapes)
{
shape.Draw();
shape.Erase();
Console.WriteLine(); // Adding a blank line for separation
}
Console.ReadLine(); // To keep the console window open
}
}
OUTPUT:
Drawing Circle
Erasing Circle
Drawing Triangle
Erasing Triangle
Drawing Square
Erasing Square
11. Develop a C# program to create an abstract class Shape with abstract methods calculateArea()
and calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and perimeter of each shape
using System;
// Triangle subclass
public class Triangle : Shape
{
Acharya Institute of Technology – Department of CS&E C# .NET Page 26
private double side1, side2, side3;
// Constructor
public Triangle(double s1, double s2, double s3)
{
side1 = s1;
side2 = s2;
side3 = s3;
}
// Implementing CalculateArea method for Triangle using Heron's formula
public override double CalculateArea()
{
double semiPerimeter = (side1 + side2 + side3) / 2;
return Math.Sqrt(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) *
(semiPerimeter - side3));
}
// Implementing CalculatePerimeter method for Triangle
public override double CalculatePerimeter()
{
return side1 + side2 + side3;
}
}
class Program
{
static void Main(string[] args)
{
// Creating a Circle object
Circle myCircle = new Circle(5);
Console.WriteLine("Circle - Area: " + myCircle.CalculateArea());
Console.WriteLine("Circle - Perimeter: " + myCircle.CalculatePerimeter());
// Creating a Triangle object
Triangle myTriangle = new Triangle(3, 4, 5);
Acharya Institute of Technology – Department of CS&E C# .NET Page 27
Console.WriteLine("\nTriangle - Area: " + myTriangle.CalculateArea());
Console.WriteLine("Triangle - Perimeter: " + myTriangle.CalculatePerimeter());
Console.ReadLine(); // To keep the console window open
}
}
OUTPUT:
Circle - Area: 78.53981633974483
Circle - Perimeter: 31.41592653589793
Triangle - Area: 6
Triangle - Perimeter: 12
12. Develop a C# program to create an interface Resizable with methods resizeWidth(int width)
and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods
using System;
// Resizable Interface
public interface IResizable
{
void ResizeWidth(int width);
void ResizeHeight(int height);
}
// Rectangle Class implementing the Resizable interface
public class Rectangle : IResizable
{
private int width;
private int height;
// Constructor
public Rectangle(int initialWidth, int initialHeight)
{
width = initialWidth;
height = initialHeight;
Good Average
a. Understanding of Demonstrate good knowledge Moderate understanding of
problem of language constructs and language constructs (1)
(3 marks) programming practice (3)
b. Execution and Program handles all possible Partial executions /poor error
testing conditions and results with handling (1)
(3marks) Satisfying results. (3)
c. Result and Meticulous documentation of Moderate formatting of output
documentation changes made and results and average documentation (1)
(2 marks) obtained are in proper format
(2)
Good Average
Conceptual Explain the complete program Adequately provides
understanding with the related concepts.(5) explanation.(3)
(2 marks)