MyBlogosphere

C# Programming Lab Solution Manual for VTU (21CSL582/ 21CBL584)

In this blog post, you will find solutions for the laboratory subject C# Programming Lab (21CSL582/ 21CBL584) course work for the V semester of VTU university. The solutions to the lab component are coded in C#. Along with the C# programs for each question I have provided samples of program output as well.

To setup the necessary developer environment for executing C# programs on the Ubuntu 22.04 platform refer to the following blog.

Syllabus

You can find the lab syllabus here.

Now lets focus on the solutions. Click on the appropriate hyperlink to go to your program of choice.

  1. Arithmetic Operations
  2. Armstrong Number
  3. Substrings in a given string
  4. Exception Demo
  5. Pascal Triangle
  6. Floyds Triangle
  7. File copy
  8. Stack Operations
  9. Complex Number Addition
  10. Polymorphism Demo
  11. Abstract Class Demo
  12. Interface Demo

Program 01 : Arithmetic Operations

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

C# Code

using System;

class Calculator
{
    static void Main()
    {
        Console.WriteLine("Simple Arithmetic Calculator");

        // Read operator and operands from the console
        Console.Write("Enter the operator (+, -, *, /, %): ");
        char operation = Console.ReadKey().KeyChar;
        Console.WriteLine(); // Move to the next line

        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;

        // Perform the selected operation
        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.");
                    return;
                }
                break;
            case '%':
                // Check for division by zero
                if (operand2 != 0)
                {
                    result = operand1 % operand2;
                }
                else
                {
                    Console.WriteLine("Error: Division by zero.");
                    return;
                }
                break;
            default:
                Console.WriteLine("Error: Invalid operator.");
                return;
        }

        // Display the result
        Console.WriteLine($"Result: {operand1} {operation} {operand2} = {result}");
    }
}

This simple arithmetic calculator showcases the basics of console-based C# applications, covering user input, conditional statements, and error handling. It serves as a foundational project for those looking to delve into C# programming and provides insights into building interactive console applications.

Commands

#Creating Project
$ dotnet new console -n ArithmeticOps

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out ArithmeticOps.csproj 

#Execution
$ ./out/ArithmeticOps

Output

$ ./out/ArithmeticOps
Simple Arithmetic Calculator
Enter the operator (+, -, *, /, %): +
Enter the first operand: 4
Enter the second operand: 5
Result: 4 + 5 = 9

$ ./out/ArithmeticOps
Simple Arithmetic Calculator
Enter the operator (+, -, *, /, %): /
Enter the first operand: 7
Enter the second operand: 6
Result: 7 / 6 = 1.1666666666666667

$ ./out/ArithmeticOps
Simple Arithmetic Calculator
Enter the operator (+, -, *, /, %): 7
Enter the first operand: 7
Enter the second operand: 9
Error: Invalid operator.

$ ./out/ArithmeticOps
Simple Arithmetic Calculator
Enter the operator (+, -, *, /, %): %
Enter the first operand: 7
Enter the second operand: 5
Result: 7 % 5 = 2

Program 02 : Armstrong Number

Develop a C# program to print Armstrong Number between 1 to 1000.

C# Code

/*using System;

class ArmstrongNumbers
{
    static void Main()
    {
        Console.WriteLine("Armstrong Numbers between 1 and 1000:");

        for (int number = 1; number <= 1000; number++)
        {
            if (IsArmstrongNumber(number))
            {
                Console.WriteLine(number);
            }
        }
    }

    static bool IsArmstrongNumber(int num)
    {
        int originalNumber = num;
        int numDigits = CountDigits(num);
        int sum = 0;

        while (num > 0)
        {
            int digit = num % 10;
            sum += (int)Math.Pow(digit, numDigits);
            num /= 10;
        }

        return originalNumber == sum;
    }

    static int CountDigits(int num)
    {
        int count = 0;

        while (num > 0)
        {
            num /= 10;
            count++;
        }

        return count;
    }
}
*/

//Without using Functions
using System;

class ArmstrongNumbers
{
    static void Main()
    {
        Console.WriteLine("Armstrong Numbers between 1 and 1000:");

        for (int number = 1; number <= 1000; number++)
        {
            int numDigits = 0;
            int temp = number;

            while (temp > 0)
            {
                temp /= 10;
                numDigits++;
            }

            temp = number;
            int sum = 0;

            while (temp > 0)
            {
                int digit = temp % 10;
                sum += (int)Math.Pow(digit, numDigits);
                temp /= 10;
            }

            if (number == sum)
            {
                Console.WriteLine(number);
            }
        }
    }
}

This C# program identifies Armstrong numbers within the range of 1 to 1000. Armstrong numbers, also known as narcissistic or pluperfect numbers, possess a unique property: the sum of each digit raised to the power of the total number of digits equals the original number.

The program iterates through numbers from 1 to 1000 using a for loop. For each number, it determines the count of digits by repeatedly dividing the number by 10 until it becomes zero. This count is crucial for the subsequent Armstrong check.

The program then decomposes the number into its digits using a while loop, raising each digit to the power calculated earlier, and summing them. If the computed sum matches the original number, it is recognized as an Armstrong number.

The output consists of the Armstrong numbers found within the specified range, providing a clear representation of these intriguing mathematical phenomena. This program serves as an illustrative example of fundamental programming constructs and their application in exploring mathematical concepts.

Commands

#Creating Project
$ dotnet new console -n Armstrong

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out Armstrong.csproj 

#Execution
$ ./out/Armstrong

Output

$ ./out/Armstrong
Armstrong Numbers between 1 and 1000:
1
2
3
4
5
6
7
8
9
153
370
371
407

Program 03 : Substrings in a given string

Develop a C# program to list all substrings in a given string. [ Hint: use of Substring() method]

C# Code

using System;

class SubstringLister
{
    static void Main()
    {
        Console.WriteLine("Enter a string:");
        string inputString = Console.ReadLine();

        // Check if the inputString is null, and if so, assign an empty string
        inputString ??= string.Empty;

        Console.WriteLine("All substrings in the given string:");

        // Loop through each character in the string
        for (int i = 0; i < inputString.Length; i++)
        {
            // Loop through each length of substring starting from the current character
            for (int j = 1; j <= inputString.Length - i; j++)
            {
                // Extract the substring using Substring(startIndex, length)
                string substring = inputString.Substring(i, j);
                Console.WriteLine(substring);
            }
        }
    }
}

The C# program is designed to take user input in the form of a string and then systematically list all possible substrings within that input string. Substrings are contiguous sequences of characters within a string.

The program utilizes nested loops to systematically enumerate all possible substrings within the given string. The outer loop iterates through each character in the string, and the inner loop considers all possible lengths of substrings starting from the current character.

Within the nested loops, the Substring method is employed to extract substrings based on the current character position and the length calculated in the inner loop. The program prints each identified substring on a new line, presenting a comprehensive list of all possible substrings within the provided string.

Commands

#Creating Project
$ dotnet new console -n SubString

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out SubString.csproj 

#Execution
$ ./out/SubString

Output

$ ./out/SubString
Enter a string:
abc
All substrings in the given string:
a
ab
abc
b
bc
c

$ ./out/SubString
Enter a string:
india
All substrings in the given string:
i
in
ind
indi
india
n
nd
ndi
ndia
d
di
dia
i
ia
a

Program 04 : Exception Demo

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

C# Code

using System;

class ExceptionDemo
{
    static void Main()
    {
        // Division by Zero Exception
        try
        {
            int numerator = 10;
            int denominator = 3;
            int result = numerator / denominator;  // Division by non zero value
            Console.WriteLine($"Result of division of {numerator}/{denominator}: {result}");
            numerator = 10;
            denominator = 0;
            result = numerator / denominator;  // Division by zero
            Console.WriteLine($"Result of division: {result}");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine($"Division by zero exception caught: {ex.Message}");
        }

        // Index Out of Range Exception
        try
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            int index = 3;  // Accessing an index that is in range
            int value = numbers[index];
            Console.WriteLine($"Value at index {index}: {value}");            
            index = 10;  // Accessing an index that is out of range
            value = numbers[index];
            Console.WriteLine($"Value at index {index}: {value}");
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"Specified Index is out of range hence out of range exception caught: {ex.Message}");
        }
    }
}

The C# program serves as a demonstration of exception handling in two scenarios: Division by Zero and Index Out of Range. Exception handling is a crucial aspect of programming that allows developers to anticipate and gracefully handle runtime errors.

Division by Zero Exception:

Index Out of Range Exception:

Exception handling is a critical aspect of robust programming, ensuring that unexpected errors are handled gracefully. This C# program provides an instructive example of handling DivideByZeroException and IndexOutOfRangeException, demonstrating how to anticipate and manage potential runtime issues effectively.

Commands

#Creating Project
$ dotnet new console -n ExceptionDemo

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out ExceptionDemo.csproj 

#Execution
$ ./out/ExceptionDemo

Output

$ ./out/ExceptionDemo
Result of division of 10/3: 3
Division by zero exception caught: Attempted to divide by zero.
Value at index 3: 4
Specified Index is out of range hence out of range exception caught: Index was outside the bounds of the array.

Program 05 : Pascal Triangle

Develop a C# program to generate and printPascal Triangle using Two Dimensional arrays.

C# Code

using System;

class PascalTriangle
{
    static void Main()
    {
        Console.WriteLine("Enter the number of rows for Pascal's Triangle:");
        int numRows = Convert.ToInt32(Console.ReadLine());

        // Create a two-dimensional array to store Pascal's Triangle
        int[,] triangle = new int[numRows, numRows];

        // Populate the array with Pascal's Triangle values
        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                if (j == 0 || j == i)
                {
                    triangle[i, j] = 1; // First and last element in each row is 1
                }
                else
                {
                    triangle[i, j] = triangle[i - 1, j - 1] + triangle[i - 1, j];
                }
            }
        }

        // Print Pascal's Triangle
        Console.WriteLine("Pascal's Triangle:");

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

The C# program generates and prints Pascal’s Triangle based on user-specified rows. Pascal’s Triangle is a mathematical construct where each number is the sum of the two numbers directly above it, forming a symmetrical pattern of binomial coefficients.

The program prompts the user to enter the desired number of rows for Pascal’s Triangle via the console. A two-dimensional array is created to store the values of Pascal’s Triangle. The array dimensions are determined by the user-provided number of rows.

Nested loops populate the array with values representing Pascal’s Triangle. Each element in the triangle is calculated based on its position, considering the sum of the two elements directly above it. Special conditions are applied for the first and last elements in each row, which are set to 1. This C# program serves as an illustrative example of generating and displaying Pascal’s Triangle. The program demonstrates the use of nested loops and a two-dimensional array to efficiently compute and present the triangle based on user input.

Commands

#Creating Project
$ dotnet new console -n PascalTriangle2D

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out PascalTriangle2D.csproj 

#Execution
$ ./out/PascalTriangle2D

Output

$ ./out/PascalTriangle2D 
Enter the number of rows for Pascal's Triangle:
6
Pascal's Triangle:
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 

$ ./out/PascalTriangle2D 
Enter the number of rows for Pascal's Triangle:
4
Pascal's Triangle:
1 
1 1 
1 2 1 
1 3 3 1 

Program 06 : Floyds Triangle

Develop a C# program to generate and print Floyds Triangle using Jagged arrays.

C# Code

using System;

class FloydsTriangle
{
    static void Main()
    {
        Console.WriteLine("Enter the number of rows for Floyd's Triangle:");
        int numRows = Convert.ToInt32(Console.ReadLine());

        // Create a jagged array to store Floyd's Triangle
        int[][] triangle = new int[numRows][];

        // Populate the jagged array with Floyd's Triangle values
        int currentNumber = 1;
        for (int i = 0; i < numRows; i++)
        {
            triangle[i] = new int[i + 1]; // Allocate space for each row

            for (int j = 0; j <= i; j++)
            {
                triangle[i][j] = currentNumber++;
            }
        }

        // Print Floyd's Triangle
        Console.WriteLine("Floyd's Triangle:");

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                Console.Write($"{triangle[i][j]} ");
            }
            Console.WriteLine();
        }
    }
}

The C# program generates and prints Floyd’s Triangle based on user-specified rows. Floyd’s Triangle is a right-angled triangular sequence of natural numbers, used for pattern-based number display. The program prompts the user to enter the desired number of rows for Floyd’s Triangle via the console.
A jagged array (an array of arrays) is created to store the values of Floyd’s Triangle. Each row in the jagged array represents a level in the triangle. Nested loops populate the jagged array with values representing Floyd’s Triangle. The completed Floyd’s Triangle is printed to the console in a formatted manner, showcasing the sequence of natural numbers.
Users execute the program, providing the number of rows for Floyd’s Triangle. The program then calculates and displays the complete Floyd’s Triangle with the specified number of rows.
This C# program provides an illustrative example of generating and displaying Floyd’s Triangle, a numerical pattern with applications in mathematics and computer science. The use of a jagged array facilitates dynamic allocation for each row, and nested loops efficiently populate and present the triangle based on user input.

Commands

#Creating Project
$ dotnet new console -n FloydsTriangle

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out FloydsTriangle.csproj 

#Execution
$ ./out/FloydsTriangle

Output

$ ./out/FloydsTriangle
Enter the number of rows for Floyd's Triangle:
5
Floyd's Triangle:
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 


$ ./out/FloydsTriangle
Enter the number of rows for Floyd's Triangle:
7
Floyd's Triangle:
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 

Program 07 : File copy

Develop a C# program to read a text file and copy the file contents to another text file.

C# Code

using System;
using System.IO;

class FileCopy
{
    static void Main()
    {
        Console.WriteLine("Enter the path of the source text file:");
        string sourceFilePath = Console.ReadLine();

        Console.WriteLine("Enter the path of the destination text file:");
        string destinationFilePath = Console.ReadLine();

        try
        {
            // Ensure the destination directory exists
            Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath));

            // 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 copy successful!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The C# program allows users to copy the contents of one text file to another. It prompts users to input the paths for the source and destination text files, ensuring the destination directory exists, and then performs the file copy operation. Exception handling is incorporated to provide a robust and error-tolerant file copying experience. The program gives clear feedback to users about the success of the file copy or any encountered errors.

The program is enclosed in a try-catch block to handle potential exceptions that may occur during file operations. This ensures graceful error handling. Before attempting to copy the file, the program ensures that the directory structure of the destination file exists. If not, it creates the necessary directory using Directory.CreateDirectory. The contents of the source file are read using File.ReadAllText and stored in a string variable (fileContents). The contents are then written to the destination file using File.WriteAllText.

Commands & Output

#Creating Project
$ dotnet new console -n FileCopy

Now go to the newly created directory using cd command

#Compiling
$ dotnet build -o out FileCopy.csproj 

#Execution
First make sure that the source file is existing. If it is in the current directory you can provide its file name, otherwise you have to provide the full path name
For the destination you need to specify the directory name followed by the destination file name.

#Source file in current directory
$ ./out/FileCopy

Enter the path of the source text file:
source.txt
Enter the path of the destination text file:
dest/recv.txt
File copy successful!

#Source file not in current directory

$ ./out/FileCopy
Enter the path of the source text file:
/home/putta/GitRepos/21csl582_c_sharp_programming/README.md
Enter the path of the destination text file:
dest/readme.txt
File copy successful!

Program 08 : Stack Operations

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]

C# Code

using System;

class StackImplementation
{
    static void Main()
    {
        // Create a stack instance
        Stack stack = new Stack();

        while (true)
        {
            Console.WriteLine("Choose an option:");
            Console.WriteLine("1. Push");
            Console.WriteLine("2. Pop");
            Console.WriteLine("3. Display");
            Console.WriteLine("4. Exit");

            int choice = GetChoice();

            switch (choice)
            {
                case 1:
                    Console.WriteLine("Enter the value to push:");
                    int valueToPush = GetValue();
                    stack.Push(valueToPush);
                    break;

                case 2:
                    int poppedValue = stack.Pop();
                    if (poppedValue != -1)
                        Console.WriteLine($"Popped element: {poppedValue}");
                    break;

                case 3:
                    stack.Display();
                    break;

                case 4:
                    Console.WriteLine("Exiting the program.");
                    Environment.Exit(0);
                    break;

                default:
                    Console.WriteLine("Invalid choice. Please choose a valid option.");
                    break;
            }
        }
    }

    static int GetChoice()
    {
        int choice;
        while (!int.TryParse(Console.ReadLine(), out choice))
        {
            Console.WriteLine("Invalid input. Please enter a number.");
        }
        return choice;
    }

    static int GetValue()
    {
        int value;
        while (!int.TryParse(Console.ReadLine(), out value))
        {
            Console.WriteLine("Invalid input. Please enter a number.");
        }
        return value;
    }
}

class Stack
{
    private const int MaxSize = 10;
    private int[] items;
    private int top;

    public Stack()
    {
        items = new int[MaxSize];
        top = -1;
    }

    public void Push(int value)
    {
        if (top == MaxSize - 1)
        {
            Console.WriteLine("Stack overflow! Cannot push more elements.");
            return;
        }

        items[++top] = value;
        Console.WriteLine($"Pushed element: {value}");
    }

    public int Pop()
    {
        if (top == -1)
        {
            Console.WriteLine("Stack underflow! Cannot pop from an empty stack.");
            return -1; // Return a sentinel value indicating underflow
        }

        int poppedValue = items[top--];
        return poppedValue;
    }

    public void Display()
    {
        if (top == -1)
        {
            Console.WriteLine("Stack is empty.");
            return;
        }

        Console.WriteLine("Stack elements:");
        for (int i = top; i >= 0; i--)
        {
            Console.WriteLine(items[i]);
        }
    }
}

The C# program demonstrates a basic implementation of a stack data structure with interactive user options. The program allows users to push elements onto the stack, pop elements off the stack, display the current stack, and exit the program.

Commands

#Creating Project
$ dotnet new console -n StackDemo

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out StackDemo.csproj 

#Execution
$ ./out/StackDemo

Output

$ ./out/StackDemo
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Stack underflow! Cannot pop from an empty stack.
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack is empty.
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
1
Enter the value to push:
12
Pushed element: 12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
1
Enter the value to push:
34
Pushed element: 34
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
1
Enter the value to push:
56
Pushed element: 56
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack elements:
56
34
12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
1
Enter the value to push:
78
Pushed element: 78
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack elements:
78
56
34
12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Popped element: 78
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack elements:
56
34
12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Popped element: 56
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack elements:
34
12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Popped element: 34
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack elements:
12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Popped element: 12
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
3
Stack is empty.
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
2
Stack underflow! Cannot pop from an empty stack.
Choose an option:
1. Push
2. Pop
3. Display
4. Exit
4
Exiting the program.

Program 09 : Complex Number Addition

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.

C# Code

using System;

class Complex
{
    private double real;
    private double imaginary;

    // Constructor
    public Complex(double real, double imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    // Overloaded addition operator
    public static Complex operator +(Complex c1, Complex c2)
    {
        double realSum = c1.real + c2.real;
        double imaginarySum = c1.imaginary + c2.imaginary;
        return new Complex(realSum, imaginarySum);
    }

    // Display the complex number
    public void Display()
    {
        Console.WriteLine($"Result: {real} + {imaginary}i");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Enter the first complex number:");
        Console.Write("Real part: ");
        double real1 = Convert.ToDouble(Console.ReadLine());
        Console.Write("Imaginary part: ");
        double imaginary1 = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("\nEnter the second complex number:");
        Console.Write("Real part: ");
        double real2 = Convert.ToDouble(Console.ReadLine());
        Console.Write("Imaginary part: ");
        double imaginary2 = Convert.ToDouble(Console.ReadLine());

        // Create Complex objects
        Complex complex1 = new Complex(real1, imaginary1);
        Complex complex2 = new Complex(real2, imaginary2);

        // Use the overloaded addition operator
        Complex result = complex1 + complex2;

        // Display the result
        Console.WriteLine("\nFirst complex number:");
        complex1.Display();
        Console.WriteLine("\nSecond complex number:");
        complex2.Display();
        Console.WriteLine("\nResult of addition:");
        result.Display();
    }
}

The C# program titled “Complex” demonstrates the implementation of a complex number class with an overloaded addition operator. The program allows users to input two complex numbers, performs the addition operation using the custom operator, and displays the result.

The program defines a Complex class with private fields real and imaginary to represent the real and imaginary parts of a complex number. The class includes a constructor to initialize the complex number with user-provided real and imaginary values. The Complex class overloads the addition operator (+) to enable the addition of two complex numbers. The addition operation involves summing the real parts and summing the imaginary parts separately. The overloaded addition operator is used to add the two complex numbers, producing a new Complex object representing the result.

Commands

#Creating Project
$ dotnet new console -n AddComplex

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out AddComplex.csproj 

#Execution
$ ./out/AddComplex

Output

$ ./out/AddComplex 
Enter the first complex number:
Real part: 6
Imaginary part: 3

Enter the second complex number:
Real part: 2
Imaginary part: 4

First complex number:
Result: 6 + 3i

Second complex number:
Result: 2 + 4i

Result of addition:
Result: 8 + 7i


$ ./out/AddComplex 
Enter the first complex number:
Real part: 3
Imaginary part: 4

Enter the second complex number:
Real part: 6
Imaginary part: -7

First complex number:
Result: 3 + 4i

Second complex number:
Result: 6 + -7i

Result of addition:
Result: 9 + -3i

Program 10 : Polymorphism Demo

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.

C# Code

using System;

class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a generic shape.");
    }

    public virtual void Erase()
    {
        Console.WriteLine("Erasing a generic shape.");
    }
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }

    public override void Erase()
    {
        Console.WriteLine("Erasing a circle.");
    }
}

class Triangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a triangle.");
    }

    public override void Erase()
    {
        Console.WriteLine("Erasing a triangle.");
    }
}

class Square : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a square.");
    }

    public override void Erase()
    {
        Console.WriteLine("Erasing a square.");
    }
}

class Program
{
    static void Main()
    {
        // Create instances of the derived classes
        Shape circle = new Circle();
        Shape triangle = new Triangle();
        Shape square = new Square();

        // Demonstrate polymorphism through the Draw and Erase methods
        Console.WriteLine("Demonstrating polymorphism:");
        DrawAndErase(circle);
        DrawAndErase(triangle);
        DrawAndErase(square);
    }

    static void DrawAndErase(Shape shape)
    {
        shape.Draw();
        shape.Erase();
        Console.WriteLine();
    }
}

The C# program titled “Shape” demonstrates the concept of polymorphism using a hierarchy of shape classes. The program defines a base class Shape and three derived classes Circle, Triangle, and Square. Through polymorphism, it showcases how the same methods, Draw and Erase, can exhibit different behaviors when invoked on objects of the derived classes.

The Shape class serves as the base class, containing virtual methods Draw and Erase that provide generic implementations. Each derived class inherits from the base class and overrides the Draw and Erase methods with specific implementations for circles, triangles, and squares. The program creates instances of the derived classes (Circle, Triangle, Square) and assigns them to variables of the base class (Shape). This demonstrates polymorphism, where objects of derived classes can be treated as objects of the base class. The DrawAndErase method is designed to accept a Shape parameter and invokes the Draw and Erase methods on that object. This showcases polymorphic behavior, where the appropriate method for the actual type of the object is called.

Commands

#Creating Project
$ dotnet new console -n PolymorphismDemo

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out PolymorphismDemo.csproj 

#Execution
$ ./out/PolymorphismDemo

Output

$ ./out/PolymorphismDemo 
Demonstrating polymorphism:
Drawing a circle.
Erasing a circle.

Drawing a triangle.
Erasing a triangle.

Drawing a square.
Erasing a square.

Program 11 : Abstract Class Demo

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.

C# Code

using System;

abstract class Shape
{
    public abstract double CalculateArea();
    public abstract double CalculatePerimeter();
}

class Circle : Shape
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

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

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

class Triangle : Shape
{
    private double side1, side2, side3;

    public Triangle(double side1, double side2, double side3)
    {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public override double CalculateArea()
    {
        // Using Heron's formula to calculate the area of a triangle
        double s = (side1 + side2 + side3) / 2;
        return Math.Sqrt(s * (s - side1) * (s - side2) * (s - side3));
    }

    public override double CalculatePerimeter()
    {
        return side1 + side2 + side3;
    }
}

class Program
{
    static void Main()
    {
        // Input for Circle
        Console.WriteLine("Enter the radius of the circle:");
        double circleRadius = Convert.ToDouble(Console.ReadLine());
        Circle circle = new Circle(circleRadius);

        // Input for Triangle
        Console.WriteLine("Enter the side lengths of the triangle (separated by spaces):");
        string[] triangleSides = Console.ReadLine().Split(' ');
        double side1 = Convert.ToDouble(triangleSides[0]);
        double side2 = Convert.ToDouble(triangleSides[1]);
        double side3 = Convert.ToDouble(triangleSides[2]);
        Triangle triangle = new Triangle(side1, side2, side3);

        // Calculate and display the area and perimeter of each shape
        Console.WriteLine("\nCircle - Area: " + circle.CalculateArea() + ", Perimeter: " + circle.CalculatePerimeter());
        Console.WriteLine("Triangle - Area: " + triangle.CalculateArea() + ", Perimeter: " + triangle.CalculatePerimeter());
    }
}

The C# program titled “ShapeCalculation” demonstrates the use of abstract classes and inheritance to model shapes (specifically, circles and triangles) with methods to calculate their areas and perimeters. Users can input parameters for a circle (radius) and a triangle (side lengths), and the program calculates and displays the respective area and perimeter for each shape.

The program defines an abstract class Shape with abstract methods CalculateArea and CalculatePerimeter. This allows for the creation of specific shape classes that implement these methods according to their individual formulas. Two derived classes, Circle and Triangle, inherit from the abstract class Shape. Each derived class provides concrete implementations for the abstract methods to calculate the area and perimeter based on the properties of circles and triangles.

This C# program demonstrates the principles of abstraction, inheritance, and polymorphism in object-oriented programming. It emphasizes the use of an abstract base class to define a common interface for different shapes, and derived classes implement specific behaviors. The program showcases the modularity and extensibility achieved through abstraction and inheritance.

Commands

#Creating Project
$ dotnet new console -n AbstractClassDemo

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out AbstractClassDemo.csproj 

#Execution
$ ./out/AbstractClassDemo

Output

$ ./out/AbstractClassDemo 
Enter the radius of the circle:
5
Enter the side lengths of the triangle (separated by spaces):
3 4 5

Circle - Area: 78.53981633974483, Perimeter: 31.41592653589793
Triangle - Area: 6, Perimeter: 12

Program 12 : Interface Demo

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.

C# Code

using System;

// Define the Resizable interface
interface Resizable
{
    void ResizeWidth(int width);
    void ResizeHeight(int height);
}

// Implement the Resizable interface in the Rectangle class
class Rectangle : Resizable
{
    private int width;
    private int height;

    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public void Display()
    {
        Console.WriteLine($"Rectangle - Width: {width}, Height: {height}");
    }

    public void ResizeWidth(int newWidth)
    {
        width = newWidth;
        Console.WriteLine($"Resized width to {newWidth}");
    }

    public void ResizeHeight(int newHeight)
    {
        height = newHeight;
        Console.WriteLine($"Resized height to {newHeight}");
    }
}

class Program
{
    static void Main()
    {
        // Input for initial values
        Console.WriteLine("Enter the initial width of the rectangle:");
        int initialWidth = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter the initial height of the rectangle:");
        int initialHeight = Convert.ToInt32(Console.ReadLine());

        // Create an instance of Rectangle
        Rectangle rectangle = new Rectangle(initialWidth, initialHeight);

        // Display the original size of the rectangle
        Console.WriteLine("\nOriginal Size:");
        rectangle.Display();

        // Input for resized values
        Console.WriteLine("\nEnter the new width for resizing:");
        int newWidth = Convert.ToInt32(Console.ReadLine());
        rectangle.ResizeWidth(newWidth);

        Console.WriteLine("Enter the new height for resizing:");
        int newHeight = Convert.ToInt32(Console.ReadLine());
        rectangle.ResizeHeight(newHeight);

        // Display the updated size of the rectangle
        Console.WriteLine("\nUpdated Size:");
        rectangle.Display();
    }
}

The C# program titled “ResizableRectangle” demonstrates the use of interfaces to implement a Resizable interface in a Rectangle class. The program allows users to create a rectangle with initial width and height values, resize its width and height interactively, and displays the updated size after each resizing operation.

The program defines a Resizable interface with methods ResizeWidth and ResizeHeight. This interface enforces the ability to resize the width and height of objects that implement it. The Rectangle class implements the Resizable interface, providing concrete implementations for resizing the width and height. The Rectangle class also has a Display method to showcase the current width and height of the rectangle.

This C# program illustrates the use of interfaces for defining a common set of behaviors (ResizeWidth and ResizeHeight) that can be implemented by different classes. The Rectangle class, implementing the Resizable interface, showcases how objects can adhere to a specific contract, providing flexibility for future enhancements or variations in behavior. The interactive nature of resizing highlights the dynamic capabilities achieved through interface implementation.

Commands

#Creating Project
$ dotnet new console -n InterfaceDemo

Now go to the newly created directory using cd command
Copy the above program into Program.cs

#Compiling
$ dotnet build -o out InterfaceDemo.csproj 

#Execution
$ ./out/InterfaceDemo

Output

$ ./out/InterfaceDemo 
Enter the initial width of the rectangle:
4
Enter the initial height of the rectangle:
8

Original Size:
Rectangle - Width: 4, Height: 8

Enter the new width for resizing:
3
Resized width to 3
Enter the new height for resizing:
6
Resized height to 6

Updated Size:
Rectangle - Width: 3, Height: 6

Prabodh C P is a faculty in the Dept of CSE SIT, Tumkur and also currently a Research Scholar pursuing PhD in IIT Hyderabad. He conducts online classes for C, C++, Python. For more info call +919392302100

Exit mobile version