0% found this document useful (0 votes)
13 views19 pages

C# Final Exp 1 To 8

Uploaded by

Aravind Krishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

C# Final Exp 1 To 8

Uploaded by

Aravind Krishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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

using System;

namespace Lab4

public class Program

public static void Main()

// Declare a jagged array

int[][] jag = new int[3][];

jag[0] = new int[2]; // First subarray has 2 elements

jag[1] = new int[4]; // Second subarray has 4 elements

jag[2] = new int[3]; // Third subarray has 3 elements

// Variables to store sums

int[] sum = new int[3]; // Array to store sum of each subarray

int result = 0; // Variable to store total sum

Console.WriteLine("Enter the values for the jagged array:");

// Input values for the jagged array

for (int i = 0; i < jag.Length; i++) // Loop over rows

Console.WriteLine($"Enter the values for row {i + 1}:");

for (int j = 0; j < jag[i].Length; j++) // Loop over columns of current row

jag[i][j] = int.Parse(Console.ReadLine()); // Read input and store in jagged array

// Calculate sum for each subarray and total sum


for (int i = 0; i < jag.Length; i++) // Loop over rows

for (int j = 0; j < jag[i].Length; j++) // Loop over columns of current row

sum[i] += jag[i][j]; // Add elements of current row

result += sum[i]; // Add row sum to total sum

// Display row-wise sums

Console.WriteLine("\nThe sum of individual rows:");

for (int i = 0; i < sum.Length; i++)

Console.WriteLine($"Row {i + 1} sum: {sum[i]}");

// Display total sum

Console.WriteLine($"\nThe total sum of all elements in the jagged array: {result}");

Console.ReadLine();

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

using System;

class Program

public static void Main(String[] args)

{
Console.WriteLine("Enter the first number:");

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

Console.WriteLine("Enter the second number:");

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

AbsChild absChild = new AbsChild();

absChild.Add(a,b);

absChild.Sub(a,b);

absChild.Mul(a,b);

absChild.Div(a,b);

public abstract class AbsParent

public void Add(int x, int y)

Console.WriteLine($"Addition of {x} and {y} is : {x + y}");

public void Sub(int x, int y)

Console.WriteLine($"Subtraction of {x} and {y} is : {x - y}");

public abstract void Mul(int x, int y);

public abstract void Div(int x, int y);

public class AbsChild : AbsParent

public override void Mul(int x, int y)

{
Console.WriteLine($"Multiplication of {x} and {y} is : {x*y}");

public override void Div(int x, int y)

Console.WriteLine($"Division of {x} and {y} is : {x/y}");

3) Implementation of inheritance and operator overloading in C#

using System;

class Shape

public virtual double CalculateArea()

return 0; // Default implementation for base class

class Circle : Shape

public double Radius { get; set; }

public Circle(double radius)

Radius = radius; // Assign the radius

public override double CalculateArea()

return Math.PI * Radius * Radius; // Area of a circle: πr²


}

public static Circle operator +(Circle c1, Circle c2)

return new Circle(c1.Radius + c2.Radius); // Combine radii

class Rectangle : Shape

public double Width { get; set; }

public double Height { get; set; }

public Rectangle(double width, double height)

Width = width;

Height = height; // Assign width and height

public override double CalculateArea()

return Width * Height; // Area of a rectangle: width × height

public static Rectangle operator +(Rectangle r1, Rectangle r2)

return new Rectangle(r1.Width + r2.Width, r1.Height + r2.Height); // Combine dimensions

class Program
{

static void Main(string[] args)

// Circle operations

Circle circle1 = new Circle(5);

Circle circle2 = new Circle(3);

Circle circleSum = circle1 + circle2; // Use overloaded + operator

// Rectangle operations

Rectangle rectangle1 = new Rectangle(4, 6);

Rectangle rectangle2 = new Rectangle(3, 8);

Rectangle rectangleSum = rectangle1 + rectangle2; // Use overloaded + operator

// Print results

Console.WriteLine("Circle 1 Area: " + circle1.CalculateArea());

Console.WriteLine("Circle 2 Area: " + circle2.CalculateArea());

Console.WriteLine("Circle Sum Area: " + circleSum.CalculateArea());

Console.WriteLine("Rectangle 1 Area: " + rectangle1.CalculateArea());

Console.WriteLine("Rectangle 2 Area: " + rectangle2.CalculateArea());

Console.WriteLine("Rectangle Sum Area: " + rectangleSum.CalculateArea());

4) Implementation of Properties and Indexer in C#

using System;

class Book

private string author;

private string title;


// Property for Title

public string Title

get { return title; }

set { title = value; }

// Property for Author

public string Author

get { return author; }

set { author = value; }

class Library

private Book[] books;

// Constructor to initialize the library with a specific size

public Library(int size)

books = new Book[size];

// Indexer to access books in the library

public Book this[int index]

get

if (index >= 0 && index < books.Length)


return books[index];

else

throw new IndexOutOfRangeException("Invalid index");

set

if (index >= 0 && index < books.Length)

books[index] = value;

else

throw new IndexOutOfRangeException("Invalid index");

// Method to display all books in the library

public void DisplayBooks()

foreach (var book in books)

if (book != null)

Console.WriteLine($"Title: {book.Title}, Author: {book.Author}");

class Program

static void Main(string[] args)

// Create a library with a capacity of 3 books


Library library = new Library(3);

// Create books

Book book1 = new Book { Title = "1984", Author = "George Orwell" };

Book book2 = new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee" };

Book book3 = new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald" };

// Add books to the library using the indexer

library[0] = book1;

library[1] = book2;

library[2] = book3;

// Display all books in the library

library.DisplayBooks();

// Access a specific book using the indexer

Console.WriteLine($"\nFirst book in the library: {library[0].Title} by {library[0].Author}");

5)a) Implementation of Delegates in C#.

using System;

delegate int Calc(int num);

public class Example

static int n = 50;

public static int sub(int num)

n = n - num;

return n;

}
public static int add(int num)

n=n + num;

return n;

public static int mul(int num)

n = n * num;

return n;

public static int div(int num)

n = n / num;

return n;

public static void Main(string[] args)

Calc a = new Calc(sub);

Calc b = new Calc(add);

Calc c = new Calc(mul);

Calc d = new Calc(div);

a(10);

Console.WriteLine("After a delegate,Number is {0}", getnum());

c(3);

Console.WriteLine("After c delegate, Number is {0}", getnum());

b(30);

Console.WriteLine("After b delegate, Number is {0}", getnum());

d(5);

Console.WriteLine("After d delegate, Number is {0}", getnum());

public static int getnum()


{

return n;

5)b) Implementation of Delegates and Events in C#.

using System;

delegate void MyEventHandler();

class MyEvent

public event MyEventHandler SomeEvent;

public void OnSomeEvent()

if(SomeEvent != null)

SomeEvent();

class EventDemo

static void Handler()

Console.WriteLine("Event Occurred");

static void Main()

MyEvent evt = new MyEvent();

evt.SomeEvent += Handler;

evt.OnSomeEvent();
}

6) Implementation of Generic Interfaces in C#.

using System;

public interface IStorage<T>

void Add(T item); // Add an item

T Get(int index); // Retrieve an item by index

public class Storage<T> : IStorage<T>

private readonly T[] items; // Private field for storing items

private int currentIndex = 0; // Private field for tracking the current index

public Storage(int size)

items = new T[size];

public void Add(T item)

if (currentIndex < items.Length)

items[currentIndex++] = item;

Console.WriteLine($"Added: {item}");

else

{
Console.WriteLine("Storage is full!");

public T Get(int index)

if (index >= 0 && index < items.Length)

return items[index];

else

throw new IndexOutOfRangeException("Invalid index");

public class Program

public static void Main()

// Storage for strings

IStorage<string> stringStorage = new Storage<string>(3);

stringStorage.Add("Apple");

stringStorage.Add("Banana");

Console.WriteLine($"Item at index 1: {stringStorage.Get(1)}");

// Storage for integers

IStorage<int> intStorage = new Storage<int>(2);

intStorage.Add(42);

intStorage.Add(100);
Console.WriteLine($"Item at index 0: {intStorage.Get(0)}");

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

using System;

public class ExceptionHandlingDemo

public static void Main()

try

Console.WriteLine("Enter the first number:");

int num1 = int.Parse(Console.ReadLine()); // May throw FormatException

Console.WriteLine("Enter the second number:");

int num2 = int.Parse(Console.ReadLine()); // May throw FormatException

int result = num1 / num2; // May throw DivideByZeroException

Console.WriteLine($"Result: {result}");

catch (FormatException ex)

Console.WriteLine("Error: Please enter a valid number.");

catch (DivideByZeroException ex)

Console.WriteLine("Error: Division by zero is not allowed.");

catch (Exception ex)


{

// General exception to catch any other unexpected errors

Console.WriteLine($"An unexpected error occurred: {ex.Message}");

finally

Console.WriteLine("Thank you for using the program.");

7) Using Try, Catch and Finally blocks write a program in C# to demonstrate errorhandling.

using System;

using System.Linq.Expressions;

using System.IO;

class Program

static void Main(string[] args)

try

int number = Convert.ToInt32("123abc");

Console.WriteLine($"Converted number :{number}");

catch (FormatException)

Console.WriteLine("Error:FormatException occurred");

try

int[] array = { 1, 2, 3 };
Console.WriteLine($"Array element at index 5:{array[5]}");

catch (IndexOutOfRangeException)

Console.WriteLine("Error:IndexOUtOFRangeException occurred");

try

string FilePath = "nonexisten.txt";

File.ReadAllText(FilePath);

catch (FileNotFoundException)

Console.WriteLine("Error: FIleNotFound exception occurred");

try

int result = Divide(100, 0);

Console.WriteLine($"Result = {result}");

catch (DivideByZeroException)

Console.WriteLine("Error: DivisionByZero occurred");

try

throw new Exception("Simulated I/O Exception");

catch (Exception ex)

{
Console.WriteLine($"An unexpected error occurred:{ex.Message}");

finally

Console.WriteLine("Cleanup and Logging can happen here");

static int Divide(int divident, int divisor)

if (divisor == 0)

throw new DivideByZeroException();

return divident / divisor;

8) Write an application to implement the Inter Thread Communication.

using System;

using System.Threading;

class Program

static object lockObject = new object();

static int sum = 0;

static bool dataProduced = false;

static void Main()

Thread producerThread = new Thread(Producer);

Thread consumerThread = new Thread(Consumer);

producerThread.Start();
consumerThread.Start();

producerThread.Join();

consumerThread.Join();

Console.WriteLine($"Sum of numbers: {sum}");

static void Producer()

lock (lockObject)

for (int i = 1; i <= 10; i++)

Console.WriteLine($"Produced:{i}");

sum += i;

dataProduced = true;

Monitor.Pulse(lockObject);

Monitor.Wait(lockObject);

dataProduced = false;

Monitor.Pulse(lockObject);

static void Consumer()

lock (lockObject)

while (!dataProduced)

Monitor.Wait(lockObject);

while (dataProduced)

Console.WriteLine($"Consumed:{sum}");
Monitor.Pulse(lockObject);

Monitor.Wait(lockObject);

You might also like