You are on page 1of 26

5 Sem C#PROGRAMMING 21CSL582

Program Statement:
1.Develop a C# program to simulate simple arithmetic calculator for Addition, Subtraction,
Multiplication, Division and Mod operations. Read the operator and operands through
console
Program:

string menu = "Simple Arithmetic Calculator\n" +


"Available operations: +, -, *, /, %";
Console.WriteLine(menu);
Console.Write("Enter the operation (e.g., +, -, *, /, %): ");
char operation = Convert.ToChar(Console.ReadLine());
Console.Write("Enter the first operand: ");
double operand1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the second operand: ");
double operand2 = Convert.ToDouble(Console.ReadLine());
double result = 0;
switch (operation){
case '+':
result = operand1 + operand2; break;
case '-':
result = operand1 - operand2;break;
case '*':
result = operand1 * operand2;break;
case '/':
// Check for division by zero
if (operand2 != 0) {
result = operand1 / operand2;}
else{
Console.WriteLine("Error: Division by zero is not allowed.");
return;
} break;
case '%':
// Check for modulus with zero
if (operand2 != 0) {
result = operand1 % operand2;}
else {
Console.WriteLine("Error: Modulus with zero is not allowed.");
return; }
break;
default:
Console.WriteLine("Error: Invalid operation.");
return;}
Console.WriteLine($"Result: {operand1} {operation} {operand2} = {result}");

Department of ISE, GSSSIETW, Mysuru Page 1


5 Sem C#PROGRAMMING 21CSL582

Output:

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 2


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
2.Develop a C# program to print Armstrong Numbers between 1 to 1000.
Program:
Console.WriteLine("Armstrong Numbers between 1 and 1000:");

int count = 1;
for (int number = 1; number <= 1000; number++)
{
if (IsArmstrongNumber(number))
{
Console.WriteLine(count + ". " + number);
count++;
}
}
bool IsArmstrongNumber(int number)
{
bool IsArmStrong = false;
int originalNumber = number;
int exponent = number.ToString().Length;
int sum = 0;
while (number > 0){
int digit = number % 10;
sum = sum + (int)Math.Pow(digit, exponent);
number = number / 10;
}
if(sum == originalNumber)
IsArmStrong = true;
return IsArmStrong;
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 3


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 4


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
3.Develop a C# program to list all substrings in a given string. [ Hint: use of Substring()
method]
Program:
Console.WriteLine("Enter the string");
string input = Console.ReadLine();
if(string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Invalid input");
return;
}
Console.WriteLine("Here are the substrings:");
int count = 1;
for (int start = 0; start < input.Length; start++)
{
for (int length = 1; length <= input.Length - start; length++)
{
//let us not consider the given string itself as a substring!
if(length == input.Length)
continue;
string subString = input.Substring(start, length);
Console.WriteLine(count + " ---> " + subString);
count++;
}
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 5


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 6


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
4.Develop a C# program to demonstrate Division by Zero and Index Out of Range
exceptions.

Program:
// Division by Zero Exception:
int numerator = 10;
int denominator = 0;
try
{
// This line will throw an exception
int result = numerator / denominator;
}
catch (DivideByZeroException ex)
{
// Handle the DivideByZeroException
Console.WriteLine(ex.Message);
}
// Index Out of Range Exception:
int[] numbers = { 1, 2, 3 };
int index = 4; // Trying to access an element at an index that is out of range
try
{
// This line will throw an exception
int num = numbers[index];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 7


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 8


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
5.Develop a C# program to print Pascal Triangle using two dimensional arrays.

Program:
Console.Clear();
Console.Write("Enter the number of rows for Pascal's Triangle: ");
int totalRows = int.Parse(Console.ReadLine());
// Initialize the 2D array
int[,] triangle = new int[totalRows, totalRows];
// Build Pascal's Triangle
for (int row = 0; row < totalRows; row++)
{
triangle[row, 0] = 1; // Every row's first column is 1
triangle[row, row] = 1; // Every row's last column is 1
for (int col = 1; col < row; col++)
{
// Set the value of each cell to the sum of the two cells above it
triangle[row, col] = triangle[row - 1, col - 1] + triangle[row - 1, col];
}
}
// Display Pascal's Triangle
for (int row = 0; row < totalRows; row++)
{
// Print leading spaces for formatting
Console.Write(new string(' ', (totalRows - row) * 2));
for (int col = 0; col <= row; col++)
{
// Print each number with spacing
Console.Write($"{triangle[row, col],4}");
}
Console.WriteLine();
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 9


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 10


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
6.Develop a C# program to generate and print Floyds Triangle using Jagged arrays.
Program:
Console.Write("Enter the number of rows for Floyd's Triangle: ");
int totalRows = int.Parse(Console.ReadLine());
// Create a jagged array
int[][] triangle = new int[totalRows][];
int currentNumber = 1;
for (int row = 0; row < totalRows; row++)
{
// Initialize each row's array
triangle[row] = new int[row + 1];
for (int col = 0; col <= row; col++)
{
// Assign the current number to the cell and increment it
triangle[row][col] = currentNumber++;
}
}
// Display Floyd's Triangle
for (int row = 0; row < totalRows; row++)
{
for (int col = 0; col < triangle[row].Length; col++)
{
Console.Write($"{triangle[row][col]} ");
}
Console.WriteLine();
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 11


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 12


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
7.Develop a C# program to read a text file and copy the file contents to another text file.
Program:
string fileRelativePath = @"..\..\..\";
string sourceFileName = "source.txt";
string destinationFileName = "destination.txt";
string sourcePath = fileRelativePath + sourceFileName;
string destinationPath = fileRelativePath + destinationFileName;
Console.Clear();
try
{
// Read all text from the source file
string content = File.ReadAllText(sourcePath);
// Write the content to the destination file
File.WriteAllText(destinationPath, content);
Console.WriteLine($"File {sourceFileName} was copied to {destinationFileName}!");
}
catch (Exception ex)
{
// If an error occurs, display an error message
Console.WriteLine("An error occurred: " + ex.Message);
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 13


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 14


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
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]
Program:
Program.cs

using StackDemo.Data;
var myStack = new Stack(5);
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine(myStack.Pop());
Console.WriteLine(myStack.Pop());
Console.WriteLine(myStack.Pop());

Stack.cs
namespace StackDemo.Data;
public class Stack(int size)
{
private int[] elements = new int[size];
private int top = -1;
private readonly int maxSize = size;
public void Push(int item)
{
if (top == maxSize - 1)
throw new InvalidOperationException("Stack overflow");
elements[++top] = item;
}
public int Pop()
{
if (top == -1)
throw new InvalidOperationException("The stack is empty");
return elements[top--];
}
}

Output:

Department of ISE, GSSSIETW, Mysuru Page 15


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 16


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
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.
Program:
Complex.cs

public class Complex(double real, double imaginary)


{
/*creating read-only properties corresponding to the parameters passed to the primary
constructor*/
public double Real { get; } = real;
public double Imaginary { get; } = imaginary;
// Overloading the binary operator '+'
public static Complex operator + (Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}

Program.cs

// Reading two complex numbers


Console.WriteLine("Enter the real and imaginary parts of the first complex number:");
var real1 = Convert.ToDouble(Console.ReadLine());
var imaginary1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the real and imaginary parts of the second complex number:");
var real2 = Convert.ToDouble(Console.ReadLine());
var imaginary2 = Convert.ToDouble(Console.ReadLine());
// Creating complex objects using primary constructor
var complex1 = new Complex(real1, imaginary1);
var complex2 = new Complex(real2, imaginary2);
// Performing addition using overloaded '+' operator
var sum = complex1 + complex2;
// Printing the result
Console.WriteLine($"Sum: {sum.Real} + {sum.Imaginary}i");

Output:

Department of ISE, GSSSIETW, Mysuru Page 17


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 18


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
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.
Program:
Shape.cs:

public abstract class Shape(string name, string color, int x, int y)


{
public string Name { get; } = name;
public string Color { get; } = color;
public int X { get; } = x;
public int Y { get; } = y;
public abstract void Draw();
public abstract void Erase();
}

Circle.cs:

public class Circle(string name, string color, int x, int y) : Shape(name, color, x, y)
{
public override void Draw()
{
Console.WriteLine($"Drawing Circle: Name - {Name}, Color - {Color}, at X: {X}, Y:
{Y}");
}
public override void Erase()
{
Console.WriteLine($"Erasing Circle: Name - {Name}");
}
}

Triangle.cs:

public class Triangle(string name, string color, int x, int y) : Shape(name, color, x, y)
{
public override void Draw()
{
Console.WriteLine($"Drawing Triangle: Name - {Name}, Color - {Color}, at X: {X},
Y:Y}");
}
public override void Erase()
{

Department of ISE, GSSSIETW, Mysuru Page 19


5 Sem C#PROGRAMMING 21CSL582

Console.WriteLine($"Erasing Triangle: Name - {Name}");


}
}

Square.cs:

public class Square(string name, string color, int x, int y) : Shape(name, color, x, y)
{
public override void Draw()
{
Console.WriteLine($"Drawing Square: Name - {Name}, Color - {Color}, at X: {X}, Y:
{Y}");
}
public override void Erase()
{
Console.WriteLine($"Erasing Square: Name - {Name}");
}
}

Program.cs:

// Create objects of each shape and demonstrate polymorphism


Shape[] shapes = {
new Circle("Circle1", "Red", 10, 20),
new Triangle("Triangle1", "Blue", 30, 40),
new Square("Square1", "Green", 50, 60)
};
// Demonstrate drawing and erasing each shape
Console.Clear();
foreach(var shape in shapes)
shape.Draw();
Console.WriteLine("-------------------");
foreach(var shape in shapes)
shape.Erase();
Console.WriteLine("-------------------");

Output:

Department of ISE, GSSSIETW, Mysuru Page 20


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 21


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
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.
Program:
Shape.cs

public abstract class Shape(string name)


{
public string Name { get; } = name;
public abstract double CalculateArea();
public abstract double CalculatePerimeter();
}

Circle.cs

public class Circle(string name, double radius) : Shape(name)


{
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
public override double CalculatePerimeter()
{
return 2 * Math.PI * radius;
}
}

Triangle.cs

public class Triangle(string name, double side1, double side2, double side3) : Shape(name)
{
public override double CalculateArea()
{
double sp = (side1 + side2 + side3) / 2;
var area = Math.Sqrt(sp * (sp - side1) * (sp - side2) * (sp - side3));
return area;
}
public override double CalculatePerimeter()
{
return side1 + side2 + side3;
}
}

Program.cs

Department of ISE, GSSSIETW, Mysuru Page 22


5 Sem C#PROGRAMMING 21CSL582

// Create objects of Circle and Triangle


var circle = new Circle("Luna", 5.0);
var triangle = new Triangle("Triforce", 3.0, 4.0, 5.0);
// Calculate and display area and perimeter for circle
Console.WriteLine($"Area of {circle.Name}: {circle.CalculateArea():F2}");
Console.WriteLine($"Perimeter of {circle.Name}: {circle.CalculatePerimeter():F2}");
// Calculate and display area and perimeter for triangle
Console.WriteLine($"Area of {triangle.Name}: {triangle.CalculateArea():F2}");
Console.WriteLine($"Perimeter of {triangle.Name}: {triangle.CalculatePerimeter():F2}");

Output:

Department of ISE, GSSSIETW, Mysuru Page 23


5 Sem C#PROGRAMMING 21CSL582

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 24


5 Sem C#PROGRAMMING 21CSL582

Program Statement:
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.
Program:

IResizable.cs

// Define the Resizable interface


public interface IResizable
{
void ResizeWidth(int width);
void ResizeHeight(int height);
}

Rectangle.cs

// Implement the Rectangle class that implements the Resizable interface


public class Rectangle(int width, int height) : IResizable
{
//Notice the use of private set, which will let us modify a variable inside the class only
public int Width { get; private set; } = width;
public int Height { get; private set; } = height;
// Methods(using lamda operators) to resize the width and height of the rectangle
public void ResizeWidth(int width) => Width = width;
public void ResizeHeight(int height) => Height = height;
}

Program.cs

var rectangle = new Rectangle(10, 20);


// Display initial dimensions
Console.WriteLine("Initial dimensions of the rectangle:");
Console.WriteLine($"Width: {rectangle.Width}, Height: {rectangle.Height}");
// Resize width and height
Console.WriteLine("\nInvoking resize methods...");
rectangle.ResizeWidth(15);
rectangle.ResizeHeight(25);
// Display dimensions after resizing
Console.WriteLine("\nDimensions after resizing the rectangle:");
Console.WriteLine($"Width: {rectangle.Width}, Height: {rectangle.Height}");

Department of ISE, GSSSIETW, Mysuru Page 25


5 Sem C#PROGRAMMING 21CSL582

Output:

Faculty Signature with Date

Department of ISE, GSSSIETW, Mysuru Page 26

You might also like