0% found this document useful (0 votes)
24 views42 pages

C# Expiriments - Copy

The document contains multiple C# programming experiments, including checking Fibonacci numbers, solving quadratic equations, calculating student marks, displaying prime numbers, and demonstrating inheritance. Each experiment provides code examples and explanations for the tasks, such as creating classes for bank accounts and persons, and implementing methods for input and output. The content is structured into levels, with increasing complexity in programming concepts.
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)
24 views42 pages

C# Expiriments - Copy

The document contains multiple C# programming experiments, including checking Fibonacci numbers, solving quadratic equations, calculating student marks, displaying prime numbers, and demonstrating inheritance. Each experiment provides code examples and explanations for the tasks, such as creating classes for bank accounts and persons, and implementing methods for input and output. The content is structured into levels, with increasing complexity in programming concepts.
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/ 42

Experiment 2: [Module 2]

Level 1: A developer wants to check whether the given input is in the


Fibonacci series or not.
// C# program to check if

// x is a perfect square

using System;

class GFG {

// A utility function that returns

// true if x is perfect square

static bool isPerfectSquare(int x)

int s = (int)Math.Sqrt(x);

return (s * s == x);

// Returns true if n is a

// Fibonacci Number, else false

static bool isFibonacci(int n)

// n is Fibonacci if one of

// 5*n*n + 4 or 5*n*n - 4 or

// both are a perfect square

return isPerfectSquare(5 * n * n + 4) ||

isPerfectSquare(5 * n * n - 4);

// Driver method

public static void Main()

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

Console.WriteLine(isFibonacci(i) ? i + " is a Fibonacci Number" : i +


" is a not Fibonacci Number"); }
}

Output:

Level 2 : Write a C# Program to implement the find the roots by solving Quadratic
Equation (-b +-√b2-4ac) / 2a.

using System; // Importing the System namespace

public class Exercise11 // Declaration of the Exercise11 class

public static void Main() // Entry point of the program

int a, b, c; // Declaration of integer variables a, b, and c for quadratic equation coefficients

double d, x1, x2; // Declaration of double variables d, x1, and x2 for discriminant and roots

Console.Write("\n\n"); // Printing new lines

Console.Write("Calculate root of Quadratic Equation :\n"); // Displaying the purpose of the


program

Console.Write("----------------------------------------"); // Displaying a separator

Console.Write("\n\n");

Console.Write("Input the value of a : "); // Prompting user to input the value of coefficient a

a = Convert.ToInt32(Console.ReadLine()); // Reading the input value of coefficient a from the


user

Console.Write("Input the value of b : "); // Prompting user to input the value of coefficient b
b = Convert.ToInt32(Console.ReadLine()); // Reading the input value of coefficient b from the
user

Console.Write("Input the value of c : "); // Prompting user to input the value of coefficient c

c = Convert.ToInt32(Console.ReadLine()); // Reading the input value of coefficient c from the


user

d = b * b - 4 * a * c; // Calculating the discriminant

if (d == 0) // Checking if the discriminant is equal to 0

Console.Write("Both roots are equal.\n"); // Printing a message if both roots are equal

x1 = -b / (2.0 * a); // Calculating the root when discriminant is zero

x2 = x1; // Assigning the same root to x2

Console.Write("First Root Root1= {0}\n", x1); // Printing the root when discriminant is zero

Console.Write("Second Root Root2= {0}\n", x2); // Printing the root when discriminant is
zero

else if (d > 0) // Checking if the discriminant is greater than 0

Console.Write("Both roots are real and different.\n"); // Printing a message if roots are real
and different

x1 = (-b + Math.Sqrt(d)) / (2 * a); // Calculating the first root

x2 = (-b - Math.Sqrt(d)) / (2 * a); // Calculating the second root

Console.Write("First Root Root1= {0}\n", x1); // Printing the first root

Console.Write("Second Root Root2= {0}\n", x2); // Printing the second root

else

Console.Write("Roots are imaginary;\nNo Solution. \n\n"); // Printing a message if roots


are imaginary

}
}

Experiment 3: [Module 2]
Level 1 : A teacher is asked to create a mark list of her class students. The class consists
of 10 students and they have 5 different subjects. Store the student’s name and five subject
marks also. Calculate the total of all subject marks and display them.

using System;

public class HelloWorld

public static void Main(string[] args)

float eng, phy,chem,math,cs;

float total,avg,per;

Console.WriteLine ("Enter 5 Subject marks");

eng=float.Parse(Console.ReadLine());

phy=float.Parse(Console.ReadLine());

chem=float.Parse(Console.ReadLine());

math=float.Parse(Console.ReadLine());

cs=float.Parse(Console.ReadLine());

total=eng+phy+chem+math+cs;

avg=total/5;

per=(total/500)*100;

Console.WriteLine("Total Scored Marks"+total);

Console.WriteLine("Average Marks"+avg);

Console.WriteLine("Total Percentage of a student "+per+"%");

}
Level 2: Write a C# Program to display all the prime numbers between 100 to 200

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace PrimeNumber

class Program

static void Main(string[] args)

bool isPrime = true;

Console.WriteLine("Prime Numbers : ");

for (int i = 100; i <= 200; i++)

for (int j = 100; j <= 200; j++)

if (i != j && i % j == 0)

{
isPrime = false;

break;

if (isPrime)

Console.Write("\t" +i);

isPrime = true;

Console.ReadKey();

Experiment 4: [Module 2]
Level 1: Design a class to represent a bank account. Include the following members:
Data Members: - Name of the depositor, Account Number, Type of Account, Balance amount
in the account and methods: To assign initial values, To deposit an amount, To withdraw an
amount after checking balance, To display name and the balance. Write a C# program to
demonstrate the working of the various class members.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;
using System.Threading.Tasks;

namespace oop3

class bank

private double balance = 100000;

public double bal

get { return balance;}

set { balance = value; }

class fuctions

bank i = new bank();

string name;

int account;

double withdraw, dep,tobal;

public void fun1()

Console.WriteLine("Enter Name of the depositor :");

name = Console.ReadLine();

Console.WriteLine("Enter Account Number :");

account = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Deposit Amount :");

dep = Convert.ToDouble(Console.ReadLine());

tobal = i.bal + dep;


Console.WriteLine("------------------------------\n");

Console.WriteLine("Name of the depositor : " + name);

Console.WriteLine("Account Number: " + account);

Console.WriteLine("Total Balance amount in the account : " +tobal);

public void fun2()

Console.WriteLine("Enter Account Name :");

name = Console.ReadLine();

Console.WriteLine("Enter Account Number :");

account = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Withdraw Amount :");

withdraw = Convert.ToDouble(Console.ReadLine());

if (withdraw <= i.bal)

tobal = i.bal - withdraw;

Console.WriteLine("------------------------------\n");

Console.WriteLine("Account Name : " + name);

Console.WriteLine("Account Number: " + account);

Console.WriteLine("After Withdraw Amount balnace is : " + tobal);

else

Console.WriteLine("\n\nWithdraw Ammount does not Exist your Account.");

class Program

static void Main(string[] args)


{

char agn;

do

fuctions k = new fuctions();

int num;

Console.WriteLine("Please Select Any Function.");

Console.WriteLine("\nPress 1 for Deposit an Amount. \nPress 2 for Withdraw an


Amount.");

num = Convert.ToInt32(Console.ReadLine());

switch (num)

case 1:

k.fun1();

break;

case 2:

k.fun2();

break;

default:

Console.WriteLine("Invalid Selection!!!");

break;

Console.WriteLine("\nDo you want to continue this program? (y/n)");

agn =Convert.ToChar(Console.ReadLine());

} while (agn == 'y');

Console.ReadKey();

}
Level 2: Define a class ‘Person’ with data members name and age. Also include
following: Default Constructor and parameterized constructor, input method which
takes values from user and assigns to data members, Output method to display all data.
Create 5 objects of ‘Person’ class using array of objects and call all the methods of a
class.
using System;

class Person

private string name;

private int age;

// Default Constructor

public Person()

name = "";
age = 0;

// Parameterized Constructor

public Person(string name, int age)

this.name = name;

this.age = age;

// Input method to take values from user

public void Input()

Console.Write("Enter name: ");

name = Console.ReadLine();

Console.Write("Enter age: ");

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

// Output method to display data

public void Output()

Console.WriteLine($"Name: {name}, Age: {age}");

class Program

static void Main()

// Create an array of 5 Person objects

Person[] persons = new Person[5];


// Using input and output methods on each object

for (int i = 0; i < 5; i++)

Console.WriteLine($"Person {i + 1}:");

persons[i] = new Person(); // Initialize the object

persons[i].Input();

Console.WriteLine("\nDisplaying Person Information:");

for (int i = 0; i < 5; i++)

persons[i].Output();

}
Experiment 5: [Module 2]
Level 1: Write a C# program to show single and multilevel inheritance.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Inherit

class inheri : vehicle

public void Noise()

Console.WriteLine("All Vehicles Creates Noise !! ");

static void Main(string[] args)

{
inheri obj = new inheri();

obj.mode();

obj.feature();

obj.Noise();

Console.Read();

class Mode

public void mode()

Console.WriteLine("There are Many Modes of Transport !!");

class vehicle : Mode

public void feature()

Console.WriteLine("They Mainly Help in Travelling !!");

using System;

// Base class

class Person

{
protected string name;

protected int age;

// Default Constructor

public Person()

name = "";

age = 0;

// Parameterized Constructor

public Person(string name, int age)

this.name = name;

this.age = age;

// Input method to take values from user

public virtual void Input()

Console.Write("Enter name: ");

name = Console.ReadLine();

Console.Write("Enter age: ");

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

// Output method to display data

public virtual void Output()

Console.WriteLine($"Name: {name}, Age: {age}");

}
// Derived class

class Emp : Person

protected int empno;

protected string position;

// Default Constructor

public Emp() : base()

empno = 0;

position = "";

// Parameterized Constructor

public Emp(string name, int age, int empno, string position) : base(name, age)

this.empno = empno;

this.position = position;

// Input method to take values from user and calls input method of Person

public override void Input()

base.Input();

Console.Write("Enter employee number: ");

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

Console.Write("Enter position: ");

position = Console.ReadLine();

// Output method to display data and calls output method of Person

public override void Output()

base.Output();

Console.WriteLine($"Employee Number: {empno}, Position: {position}");


}

// Derived class

class Manager : Emp

private double bonus;

// Default Constructor

public Manager() : base()

bonus = 0.0;

// Parameterized Constructor

public Manager(string name, int age, int empno, string position, double bonus) : base(name,
age, empno, position)

this.bonus = bonus;

// Input method to take values from user and calls input method of Emp

public override void Input()

base.Input();

Console.Write("Enter bonus: ");

bonus = double.Parse(Console.ReadLine());

// Output method to display data and calls output method of Emp

public override void Output()

base.Output();

Console.WriteLine($"Bonus: {bonus}");

}
}

class Program

static void Main()

// Create a Manager object

Manager manager = new Manager();

// Use input method to take user input

Console.WriteLine("Enter Manager Details:");

manager.Input();

// Display the details of the manager

Console.WriteLine("\nManager Details:");

manager.Output();

Level 2: Create a class ‘Emp’ by extending Person class with additional data member
empno, position with following features:
a. Default constructor
b. Parameterized constructor
c. Input method which takes values from user and assigns to data members and calls
input method of Person
d. Output method to display all data and calls output method of Person
Define a class Manager by extending Emp with data member bonus. Provide necessary
constructors and override input and output methods. Create objects of manager in main
using System;

// Base class

class Person

protected string name;

protected int age;

// Default Constructor

public Person()

{
name = "";

age = 0;

// Parameterized Constructor

public Person(string name, int age)

this.name = name;

this.age = age;

// Input method to take values from user

public virtual void Input()

Console.Write("Enter name: ");

name = Console.ReadLine();

Console.Write("Enter age: ");

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

// Output method to display data

public virtual void Output()

Console.WriteLine($"Name: {name}, Age: {age}");

// Derived class

class Emp : Person

protected int empno;

protected string position;

// Default Constructor

public Emp() : base()

{
empno = 0;

position = "";

// Parameterized Constructor

public Emp(string name, int age, int empno, string position) : base(name, age)

this.empno = empno;

this.position = position;

// Input method to take values from user and calls input method of Person

public override void Input()

base.Input();

Console.Write("Enter employee number: ");

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

Console.Write("Enter position: ");

position = Console.ReadLine();

// Output method to display data and calls output method of Person

public override void Output()

base.Output();

Console.WriteLine($"Employee Number: {empno}, Position: {position}");

// Derived class

class Manager : Emp

private double bonus;

// Default Constructor

public Manager() : base()


{

bonus = 0.0;

// Parameterized Constructor

public Manager(string name, int age, int empno, string position, double bonus) : base(name,
age, empno, position)

this.bonus = bonus;

// Input method to take values from user and calls input method of Emp

public override void Input()

base.Input();

Console.Write("Enter bonus: ");

bonus = double.Parse(Console.ReadLine());

// Output method to display data and calls output method of Emp

public override void Output()

base.Output();

Console.WriteLine($"Bonus: {bonus}");

class Program

static void Main()

// Create a Manager object

Manager manager = new Manager();

// Use input method to take user input


Console.WriteLine("Enter Manager Details:");

manager.Input();

// Display the details of the manager

Console.WriteLine("\nManager Details:");

manager.Output();

Experiment 6: [Module 2]
Level 1: Calculate the area of different shapes using method overloading.
using System;

class Shape

// Method to calculate area of a square

public double CalculateArea(double side)

return side * side;

// Method to calculate area of a rectangle

public double CalculateArea(double length, double width)

{
return length * width;

// Method to calculate area of a circle

public double CalculateArea(double radius, bool isCircle)

return Math.PI * radius * radius;

// Method to calculate area of a triangle

public double CalculateArea(double baseLength, double height, bool isTriangle)

return 0.5 * baseLength * height;

class Program

static void Main()

Shape shape = new Shape();

// Calculate area of a square

double squareSide = 5;

double squareArea = shape.CalculateArea(squareSide);

Console.WriteLine($"Area of the square with side {squareSide} is {squareArea}");

// Calculate area of a rectangle

double rectangleLength = 10;

double rectangleWidth = 5;

double rectangleArea = shape.CalculateArea(rectangleLength, rectangleWidth);


Console.WriteLine($"Area of the rectangle with length {rectangleLength} and width
{rectangleWidth} is {rectangleArea}");

// Calculate area of a circle

double circleRadius = 7;

double circleArea = shape.CalculateArea(circleRadius, true);

Console.WriteLine($"Area of the circle with radius {circleRadius} is {circleArea}");

// Calculate area of a triangle

double triangleBase = 8;

double triangleHeight = 6;

double triangleArea = shape.CalculateArea(triangleBase, triangleHeight, true);

Console.WriteLine($"Area of the triangle with base {triangleBase} and height {triangleHeight}


is {triangleArea}");

Level 2: The class teacher created different groups in a class and store the data in that. In
order to make common announcements and activities, the teacher merged all data into a
single group. Write a code to merge two groups into one.

using System;

using System.Collections.Generic;

class Program

static void Main()

// Define the first group

List<string> group1 = new List<string> { "Alice", "Bob", "Charlie" };

// Define the second group

List<string> group2 = new List<string> { "David", "Eva", "Frank" };

// Merge the two groups

List<string> mergedGroup = MergeGroups(group1, group2);

// Display the merged group

Console.WriteLine("Merged Group:");

foreach (string student in mergedGroup)


{

Console.WriteLine(student);

static List<string> MergeGroups(List<string> group1, List<string> group2)

// Create a new list to hold the merged group

List<string> mergedGroup = new List<string>(group1);

// Add the second group to the merged group

mergedGroup.AddRange(group2);

return mergedGroup;

Experiment 7: [Module 2]
Level 1: Class Teacher stores students marks in an array. The teacher is searching for highest
and lowest marks of the class and the number of students who scored those marks. Write a
program to help teacher to do the same.

using System;

class Program

static void Main()

// Example array of student marks

int[] marks = { 85, 92, 78, 92, 56, 78, 100, 100, 45, 56, 92 };
// Find the highest and lowest marks

int highestMark = FindHighestMark(marks);

int lowestMark = FindLowestMark(marks);

// Count the number of students who scored the highest and lowest marks

int highestMarkCount = CountOccurrences(marks, highestMark);

int lowestMarkCount = CountOccurrences(marks, lowestMark);

// Display the results

Console.WriteLine($"Highest Mark: {highestMark}");

Console.WriteLine($"Number of students who scored the highest mark:


{highestMarkCount}");

Console.WriteLine($"Lowest Mark: {lowestMark}");

Console.WriteLine($"Number of students who scored the lowest mark: {lowestMarkCount}");

static int FindHighestMark(int[] marks)

int highest = marks[0];

foreach (int mark in marks)

if (mark > highest)

highest = mark;

return highest;

static int FindLowestMark(int[] marks)


{

int lowest = marks[0];

foreach (int mark in marks)

if (mark < lowest)

lowest = mark;

return lowest;

static int CountOccurrences(int[] marks, int targetMark)

int count = 0;

foreach (int mark in marks)

if (mark == targetMark)

count++;

return count;

}
Level 2: Create an application for the currency converter.

using System;
using System.Collections.Generic;

namespace CurrencyConverter
{
class Program
{
static Dictionary<string, double> exchangeRates = new Dictionary<string,
double>
{
{ "USD", 1.0 },
{ "EUR", 0.85 },
{ "JPY", 110.0 },
{ "GBP", 0.75 },
{ "AUD", 1.35 },
{ "CAD", 1.25 },
{ "CHF", 0.92 },
{ "CNY", 6.45 },
{ "SEK", 8.55 },
{ "NZD", 1.45 }
};

static void Main(string[] args)


{
if (args.Length != 3)
{
Console.WriteLine("Usage: CurrencyConverter <amount>
<from_currency> <to_currency>");
return;
}

if (!double.TryParse(args[0], out double amount))


{
Console.WriteLine("Error: Amount must be a number.");
return;
}

string fromCurrency = args[1].ToUpper();


string toCurrency = args[2].ToUpper();

if (!exchangeRates.ContainsKey(fromCurrency) || !
exchangeRates.ContainsKey(toCurrency))
{
Console.WriteLine($"Error: Unsupported currency code '{fromCurrency}'
or '{toCurrency}'.");
return;
}

double convertedAmount = ConvertCurrency(amount, fromCurrency,


toCurrency);
Console.WriteLine($"{amount} {fromCurrency} is equivalent to
{convertedAmount:F2} {toCurrency}");
}

static double ConvertCurrency(double amount, string fromCurrency, string


toCurrency)
{
double amountInUSD = amount / exchangeRates[fromCurrency];
double convertedAmount = amountInUSD * exchangeRates[toCurrency];
return convertedAmount;
}
}
}

Experiment 8: [Module 3]
Level 1: EC is updating its database of new voters. If the user’s age is less than 18, the
application should raise the exception.
using System;

namespace VoterRegistration
{
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();

Console.Write("Enter your age: ");


if (!int.TryParse(Console.ReadLine(), out int age))
{
throw new Exception("Invalid input for age. Age must be a number.");
}

RegisterVoter(name, age);

Console.WriteLine("Voter registration successful.");


}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}

static void RegisterVoter(string name, int age)


{
if (age < 18)
{
throw new Exception("Voter must be at least 18 years old to register.");
}

// Here you would normally add the voter to the database


// For this example, we just print a confirmation message
Console.WriteLine($"Voter {name}, age {age}, has been registered.");
}
}
}

Level 2: Write a multithreaded program to display odd and even numbers in different threads.
using System;
using System.Threading;

namespace OddEvenMultithreading
{
class Program
{
static void Main(string[] args)
{
// Create threads for displaying odd and even numbers
Thread oddThread = new Thread(DisplayOddNumbers);
Thread evenThread = new Thread(DisplayEvenNumbers);
// Start the threads
oddThread.Start();
evenThread.Start();
// Wait for both threads to finish
oddThread.Join();
evenThread.Join();
Console.WriteLine("Finished displaying odd and even numbers.");
}
static void DisplayOddNumbers()
{
for (int i = 1; i <= 20; i += 2)
{
Console.WriteLine($"Odd: {i}");
Thread.Sleep(100); // Sleep to simulate work
}
}
static void DisplayEvenNumbers()
{
for (int i = 2; i <= 20; i += 2)
{
Console.WriteLine($"Even: {i}");
Thread.Sleep(100); // Sleep to simulate work
}
}
}
}

Experiment 9: [Module 3]

Level 1: Write a C# Program to call any method that agrees with its signature and return type
using delegate
using System;

namespace DelegateExample
{
// Define a delegate that takes two integers and returns an integer
public delegate int Operation(int x, int y);

class Program
{
static void Main(string[] args)
{
// Instantiate the delegate with the Add method
Operation operation = Add;
Console.WriteLine($"Add: {operation(5, 3)}");

// Reassign the delegate to the Subtract method


operation = Subtract;
Console.WriteLine($"Subtract: {operation(5, 3)}");

// Reassign the delegate to the Multiply method


operation = Multiply;
Console.WriteLine($"Multiply: {operation(5, 3)}");

// Reassign the delegate to the Divide method


operation = Divide;
Console.WriteLine($"Divide: {operation(10, 2)}");

// Try to divide by zero and handle the exception


try
{
Console.WriteLine($"Divide by zero: {operation(10, 0)}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}

// Method that matches the delegate signature and return type


static int Add(int x, int y)
{
return x + y;
}
// Another method that matches the delegate signature and return type
static int Subtract(int x, int y)
{
return x - y;
}

// Another method that matches the delegate signature and return type
static int Multiply(int x, int y)
{
return x * y;
}

// Another method that matches the delegate signature and return type
static int Divide(int x, int y)
{
if (y == 0)
throw new DivideByZeroException("Division by zero is not allowed.");
return x / y;
}
}
}
Level 2: Write a program that uses delegates and event mechanisms to fire, wire, and handle
an event.
using System;

namespace EventDemo
{
// Define a delegate for the event
public delegate void ThresholdReachedEventHandler(object sender,
ThresholdReachedEventArgs e);

// Define a class to hold custom event info


public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}

// Publisher class
public class Publisher
{
private int _total;
private int _threshold;

// Declare the event using the delegate


public event ThresholdReachedEventHandler ThresholdReached;

public Publisher(int threshold)


{
_threshold = threshold;
}

public void Add(int x)


{
_total += x;
if (_total >= _threshold)
{
// Raise the event
OnThresholdReached(new ThresholdReachedEventArgs
{
Threshold = _threshold,
TimeReached = DateTime.Now
});
}
}

protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)


{
ThresholdReached?.Invoke(this, e);
}
}

// Subscriber class
public class Subscriber
{
public void OnThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine($"Threshold reached! Threshold: {e.Threshold}, Time:
{e.TimeReached}");
}
}

class Program
{
static void Main(string[] args)
{
// Create an instance of the publisher with a threshold
Publisher publisher = new Publisher(10);

// Create an instance of the subscriber


Subscriber subscriber = new Subscriber();

// Wire the event


publisher.ThresholdReached += subscriber.OnThresholdReached;

// Simulate adding values


Console.WriteLine("Adding values...");
for (int i = 1; i <= 10; i++)
{
publisher.Add(i);
}

Console.WriteLine("Finished adding values.");


}
}
}

Experiment 10: [Module 3]


Level1: Write a C# Program to use of an anonymous method that count from 0 to 10
using System;

namespace AnonymousMethodDemo
{
class Program
{
// Define a delegate that takes no parameters and returns void
delegate void CountDelegate();

static void Main(string[] args)


{
// Instantiate the delegate with an anonymous method
CountDelegate count = delegate
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(i);
}
};

// Call the delegate to execute the anonymous method


count();

Console.WriteLine("Finished counting from 0 to 10.");


}
}
}
Level 2: Write a multithreaded program to explain the concepts of thread communication
using System;

using System;
using System.Collections.Generic;
using System.Threading;

namespace ThreadCommunicationDemo
{
class Program
{
// Shared queue for producer-consumer communication
private static Queue<int> sharedQueue = new Queue<int>();
private static object queueLock = new object();
private static bool done = false;
static void Main(string[] args)
{
// Create and start producer and consumer threads
Thread producerThread = new Thread(Producer);
Thread consumerThread = new Thread(Consumer);
producerThread.Start();
consumerThread.Start();
// Wait for both threads to complete
producerThread.Join();
consumerThread.Join();
Console.WriteLine("Producer and consumer threads have completed.");
}
static void Producer()
{
for (int i = 0; i < 10; i++)
{
lock (queueLock)
{
sharedQueue.Enqueue(i);
Console.WriteLine($"Produced: {i}");
Monitor.Pulse(queueLock); // Notify the consumer
}
Thread.Sleep(500); // Simulate production time
}
lock (queueLock)
{
done = true;
Monitor.Pulse(queueLock); // Notify the consumer that production is done
}
}
static void Consumer()
{
while (true)
{
int item;
lock (queueLock)
{
while (sharedQueue.Count == 0 && !done)
{
Monitor.Wait(queueLock); // Wait for an item to be produced
}

if (sharedQueue.Count == 0 && done)


{
break; // Exit if done and no more items to consume
}

item = sharedQueue.Dequeue();
}

Console.WriteLine($"Consumed: {item}");
Thread.Sleep(300); // Simulate consumption time
}
}
}
}

You might also like