C# Expiriments - Copy
C# Expiriments - Copy
// x is a perfect square
using System;
class GFG {
int s = (int)Math.Sqrt(x);
return (s * s == x);
// Returns true if n is a
// n is Fibonacci if one of
// 5*n*n + 4 or 5*n*n - 4 or
return isPerfectSquare(5 * n * n + 4) ||
isPerfectSquare(5 * n * n - 4);
// Driver method
Output:
Level 2 : Write a C# Program to implement the find the roots by solving Quadratic
Equation (-b +-√b2-4ac) / 2a.
double d, x1, x2; // Declaration of double variables d, x1, and x2 for discriminant and roots
Console.Write("\n\n");
Console.Write("Input the value of a : "); // Prompting user to input the value of coefficient a
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
Console.Write("Both roots are equal.\n"); // Printing a message if both roots are equal
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
Console.Write("Both roots are real and different.\n"); // Printing a message if roots are real
and different
else
}
}
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;
float total,avg,per;
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("Average Marks"+avg);
}
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
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
class fuctions
string name;
int account;
name = Console.ReadLine();
account = Convert.ToInt32(Console.ReadLine());
dep = Convert.ToDouble(Console.ReadLine());
name = Console.ReadLine();
account = Convert.ToInt32(Console.ReadLine());
withdraw = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("------------------------------\n");
else
class Program
char agn;
do
int num;
num = Convert.ToInt32(Console.ReadLine());
switch (num)
case 1:
k.fun1();
break;
case 2:
k.fun2();
break;
default:
Console.WriteLine("Invalid Selection!!!");
break;
agn =Convert.ToChar(Console.ReadLine());
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
// Default Constructor
public Person()
name = "";
age = 0;
// Parameterized Constructor
this.name = name;
this.age = age;
name = Console.ReadLine();
age = int.Parse(Console.ReadLine());
class Program
Console.WriteLine($"Person {i + 1}:");
persons[i].Input();
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
{
inheri obj = new inheri();
obj.mode();
obj.feature();
obj.Noise();
Console.Read();
class Mode
using System;
// Base class
class Person
{
protected string name;
// Default Constructor
public Person()
name = "";
age = 0;
// Parameterized Constructor
this.name = name;
this.age = age;
name = Console.ReadLine();
age = int.Parse(Console.ReadLine());
}
// Derived class
// Default Constructor
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
base.Input();
empno = int.Parse(Console.ReadLine());
position = Console.ReadLine();
base.Output();
// Derived class
// Default Constructor
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
base.Input();
bonus = double.Parse(Console.ReadLine());
base.Output();
Console.WriteLine($"Bonus: {bonus}");
}
}
class Program
manager.Input();
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
// Default Constructor
public Person()
{
name = "";
age = 0;
// Parameterized Constructor
this.name = name;
this.age = age;
name = Console.ReadLine();
age = int.Parse(Console.ReadLine());
// Derived class
// Default Constructor
{
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
base.Input();
empno = int.Parse(Console.ReadLine());
position = Console.ReadLine();
base.Output();
// Derived class
// Default Constructor
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
base.Input();
bonus = double.Parse(Console.ReadLine());
base.Output();
Console.WriteLine($"Bonus: {bonus}");
class Program
manager.Input();
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
{
return length * width;
class Program
double squareSide = 5;
double rectangleWidth = 5;
double circleRadius = 7;
double triangleBase = 8;
double triangleHeight = 6;
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
Console.WriteLine("Merged Group:");
Console.WriteLine(student);
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
int[] marks = { 85, 92, 78, 92, 56, 78, 100, 100, 45, 56, 92 };
// Find the highest and lowest marks
// Count the number of students who scored the highest and lowest marks
highest = mark;
return highest;
lowest = mark;
return lowest;
int count = 0;
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 }
};
if (!exchangeRates.ContainsKey(fromCurrency) || !
exchangeRates.ContainsKey(toCurrency))
{
Console.WriteLine($"Error: Unsupported currency code '{fromCurrency}'
or '{toCurrency}'.");
return;
}
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();
RegisterVoter(name, age);
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)}");
// 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);
// Publisher class
public class Publisher
{
private int _total;
private int _threshold;
// 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);
namespace AnonymousMethodDemo
{
class Program
{
// Define a delegate that takes no parameters and returns void
delegate void CountDelegate();
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
}
item = sharedQueue.Dequeue();
}
Console.WriteLine($"Consumed: {item}");
Thread.Sleep(300); // Simulate consumption time
}
}
}
}