0% found this document useful (0 votes)
8 views43 pages

C# RECORD

The document contains three C# programs: the first manages student details, attendance, and marks; the second implements an inventory control system for purchasing and selling items; and the third is a calculator that supports basic arithmetic operations and maintains a history of results. Each program includes user interaction through the console for input and output, demonstrating object-oriented programming concepts such as classes, inheritance, and interfaces. The outputs provide examples of how each program operates with sample data.

Uploaded by

lhemachandran908
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)
8 views43 pages

C# RECORD

The document contains three C# programs: the first manages student details, attendance, and marks; the second implements an inventory control system for purchasing and selling items; and the third is a calculator that supports basic arithmetic operations and maintains a history of results. Each program includes user interaction through the console for input and output, demonstrating object-oriented programming concepts such as classes, inheritance, and interfaces. The outputs provide examples of how each program operates with sample data.

Uploaded by

lhemachandran908
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/ 43

PROGRAM 1:

using System;

class Student
{
public string name = "";
public int roll;
public int[] marks = new int[3];
public int[] ia = new int[3];
public int[] att = new int[3];
const int PASS_MARK = 40;
public void EnterDetails()
{
Console.Write("Enter Student Name: ");
name = Console.ReadLine();

Console.Write("Enter Roll Number: ");


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

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


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

do
{
Console.Write("Enter Internal Assessment (Out of 25): ");
ia[i] = int.Parse(Console.ReadLine());
if (ia[i] <= 0 || ia[i] > 25)
{
Console.WriteLine("Invalid input! IA marks should be between 1 and 25.");
}
} while (ia[i] <= 0 || ia[i] > 25);

do
{
Console.Write("Enter Attendance Percentage: ");
att[i] = int.Parse(Console.ReadLine());
if (att[i] < 0 || att[i] > 100)
{
Console.WriteLine("Invalid input! Attendance should be between 0 and 100.");
}
} while (att[i] < 0 || att[i] > 100);
if (ia[i] > 0 && att[i] >= 75)
{
do
{
Console.Write("Enter Marks (Out of 75): ");
marks[i] = int.Parse(Console.ReadLine());
if (marks[i] < 0 || marks[i] > 75)
{
Console.WriteLine("Invalid input! Marks should be between 0 and 75.");
}
} while (marks[i] < 0 || marks[i] > 75);
}
else
{
marks[i] = -1;
}
}
}

public void DisplayAttendanceReport()


{
Console.WriteLine($"\n------------------------------");
Console.WriteLine($"Attendance Report for {name} (Roll No: {roll})");
Console.WriteLine($"------------------------------");
for (int i = 0; i < 3; i++)
{
string status = (ia[i] > 0 && att[i] >= 75) ? "Eligible for Exam" : "Not Eligible for
Exam";
Console.WriteLine($"Subject {i + 1}: Attendance {att[i]}%, Status: {status}");
}
}

public void DisplayMarkList()


{
Console.WriteLine($"\n------------------------------");
Console.WriteLine($"Mark List for {name} (Roll No: {roll})");
Console.WriteLine($"------------------------------");
int total = 0;
int passed = 0;
for (int i = 0; i < 3; i++)
{
if (marks[i] >= 0)
{
int totalMark = marks[i] + ia[i];
total += totalMark;
string passStatus = totalMark >= PASS_MARK ? "Pass" : "Fail";
if (totalMark >= PASS_MARK) passed++;
Console.WriteLine($"Subject {i + 1}: {totalMark}/100 - {passStatus}");
}
else
{
Console.WriteLine($"Subject {i + 1}: 0");
}
}
string overallStatus = passed == 3 ? "Pass" : "Fail";
Console.WriteLine($"Total Marks: {total}/300 - Overall Status: {overallStatus}");
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter number of students: ");
int count = int.Parse(Console.ReadLine());

Student[] students = new Student[count];

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


{
Console.WriteLine($"\nEnter details for Student {i + 1}:");
students[i] = new Student();
students[i].EnterDetails();
}
while (true)
{
Console.WriteLine("\nChoose Report Type:");
Console.WriteLine("1. Attendance Report");
Console.WriteLine("2. Mark List");
Console.WriteLine("3. Exit");
Console.Write("Enter your choice: ");

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

if (choice == 3)
{
Console.WriteLine("Exiting the Program");
break;
}

foreach (var student in students)


{
if (choice == 1)
{
student.DisplayAttendanceReport();
}
else if (choice == 2)
{
student.DisplayMarkList();
}
else
{
Console.WriteLine("Invalid choice! Please try again.");
break;
}
}
}
}
}
OUTPUT:

Enter number of students: 1


Enter details for Student 1:
Enter Student Name: John
Enter Roll Number: 112

Subject 1:
Enter Internal Assessment (Out of 25): 24
Enter Attendance Percentage: 79
Enter Marks (Out of 75): 69

Subject 2:
Enter Internal Assessment (Out of 25): 19
Enter Attendance Percentage: 56

Subject 3:
Enter Internal Assessment (Out of 25): 22
Enter Attendance Percentage: 89
Enter Marks (Out of 75): 23

Choose Report Type:


1. Attendance Report
2. Mark List
3. Exit
Enter your choice: 1

--------------------------------------------------------
Attendance Report for John (Roll No: 112)
--------------------------------------------------------
Subject 1: Attendance 79%, Status: Eligible for Exam
Subject 2: Attendance 56%, Status: Not Eligible for Exam
Subject 3: Attendance 89%, Status: Eligible for Exam

Choose Report Type:


1. Attendance Report
2. Mark List
3. Exit
Enter your choice: 2
-------------------------------------------
Mark List for John (Roll No: 112)
-------------------------------------------
Subject 1: 93/100 - Pass
Subject 2: 0
Subject 3: 45/100 - Pass
Total Marks: 138/300 - Overall Status: Fail

Choose Report Type:


1. Attendance Report
2. Mark List
3. Exit
Enter your choice: 3
Exiting the Program
PROGRAM 2:
using System;

interface Inventory
{
void DisplayInfo();
}
class ItemDescription : Inventory // Base Class: Item Description
{
public int ItemID;
public string Name;
public double Price;

public ItemDescription(int id, string name, double price)


{
ItemID = id;
Name = name;
Price = price;
}

public void DisplayInfo()


{
Console.WriteLine("\n====================================");
Console.WriteLine($" ID: {ItemID}\n Name: {Name}\n Price: {Price:C}");
Console.WriteLine("====================================");
}
}

class Stock : ItemDescription // Stock Class (Inherits ItemDescription)


{
public int Quantity;

public Stock(int id, string name, double price, int quantity)


: base(id, name, price)
{
Quantity = quantity;
}

public void UpdateStock(int amount)


{
Quantity += amount;
Console.WriteLine($"\nStock updated successfully! New Quantity: {Quantity}\n");
}
}
class Sales : Stock // Sales Class (Inherits Stock)
{
public Sales(int id, string name, double price, int quantity)
: base(id, name, price, quantity) { }

public void SellItem(int quantity)


{
if (Quantity >= quantity)
{
double totalCost = quantity * Price;
Quantity -= quantity; // Update stock directly
Console.WriteLine("\n====================================");
Console.WriteLine(" Product Sold Successfully! ");
Console.WriteLine("====================================");
Console.WriteLine($" Product: {Name}\n Quantity Sold: {quantity}\n Total Cost:
{totalCost:C}");
Console.WriteLine("====================================\n");
}
else
{
Console.WriteLine("\nNot enough stock available!\n");
}
}
}

class Program
{
static void Main()
{
Sales[] stockItems = new Sales[10]; // Fixed-size array for 10 products
int productCount = 0;

while (true)
{
Console.WriteLine("\n====================================");
Console.WriteLine(" Inventory Control System ");
Console.WriteLine("====================================");
Console.WriteLine("1. Purchase Items (Add New Stock)");
Console.WriteLine("2. Sell Items");
Console.WriteLine("3. Display Stock");
Console.WriteLine("4. Exit");
Console.WriteLine("====================================");
Console.Write("Choose an option: ");
int choice = Convert.ToInt32(Console.ReadLine());

switch (choice)
{
case 1: // Purchase Items
if (productCount >= stockItems.Length)
{
Console.WriteLine("\nInventory is full! Cannot add more products.\n");
break;
}

Console.Write("\nEnter Item ID: ");


int id = Convert.ToInt32(Console.ReadLine());

string? name;
do
{
Console.Write("Enter Name: ");
name = Console.ReadLine();
} while (string.IsNullOrWhiteSpace(name));

Console.Write("Enter Price: ");


double price = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter Quantity: ");


int quantity = Convert.ToInt32(Console.ReadLine());

bool found = false;


for (int i = 0; i < productCount; i++)
{
if (stockItems[i].Name == name)
{
stockItems[i].UpdateStock(quantity);
found = true;
break;
}
}
if (!found)
{
stockItems[productCount] = new Sales(id, name, price, quantity);
productCount++;
}

Console.WriteLine("\nStock purchased successfully!\n");


break;

case 2: // Sell Items

string? productName;
do
{
Console.Write("Enter Product Name: ");
productName = Console.ReadLine();
} while (string.IsNullOrWhiteSpace(productName));

bool itemSold = false;

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


{
if (stockItems[i].Name == productName)
{
Console.Write("Enter Quantity to sell: ");
int sellQuantity = Convert.ToInt32(Console.ReadLine());
stockItems[i].SellItem(sellQuantity);
itemSold = true;
break;
}
}

if (!itemSold)
{
Console.WriteLine("\nProduct not found in stock!\n");
}
break;
case 3: // Display Stock
if (productCount == 0)
{
Console.WriteLine("\nNo stock available!\n");
break;
}

Console.WriteLine("\nCurrent Stock:");
for (int i = 0; i < productCount; i++)
{
stockItems[i].DisplayInfo();
Console.WriteLine($"Stock Quantity: {stockItems[i].Quantity}\n");
}
break;
case 4:
Console.WriteLine("\nExiting...\n");
return;

default:
Console.WriteLine("\nInvalid choice! Try again.\n");
break;
}
}
}
}
OUTPUT:

====================================
Inventory Control System
====================================
1. Purchase Items (Add New Stock)
2. Sell Items
3. Display Stock
4. Exit
====================================
Choose an option: 1

Enter Item ID: 101


Enter Name: Salt
Enter Price: 70
Enter Quantity: 10

Stock purchased successfully!

====================================
Inventory Control System
====================================
1. Purchase Items (Add New Stock)
2. Sell Items
3. Display Stock
4. Exit
====================================
Choose an option: 2
Enter Product Name: Salt
Enter Quantity to sell: 3

====================================
Product Sold Successfully!
====================================
Product: Salt
Quantity Sold: 3
Total Cost: $210.00
====================================
====================================
Inventory Control System
====================================
1. Purchase Items (Add New Stock)
2. Sell Items
3. Display Stock
4. Exit
====================================
Choose an option: 3

Current Stock:
====================================
ID: 101
Name: Salt
Price: $70.00
====================================
Stock Quantity: 7

====================================
Inventory Control System
====================================
1. Purchase Items (Add New Stock)
2. Sell Items
3. Display Stock
4. Exit
====================================
Choose an option: 4

Exiting...
PROGRAM 3:
using System;

namespace ArithmeticCalc
{
public class Calculator
{
private readonly double[] history = new double[10];
private int historyIndex;

public double this[int index]


{
get
{
int count = Math.Min(history.Length, historyIndex); // Limit to stored results
if (index >= 0 && index < count)
{
return history[(historyIndex - count + index) % history.Length];
}
throw new IndexOutOfRangeException("History index out of range.");
}
}

private void StoreResult(double result) => history[historyIndex++ % history.Length] =


result;

// Method overloading for different data types


public static int Add(int a, int b) => a + b;
public static double Add(double a, double b) => a + b;

public static int Subtract(int a, int b) => a - b;


public static double Subtract(double a, double b) => a - b;

public static int Multiply(int a, int b) => a * b;


public static double Multiply(double a, double b) => a * b;
public static int Divide(int a, int b) => b == 0 ? throw new
DivideByZeroException("Cannot divide by zero.") : a / b;

public static double Divide(double a, double b) => b == 0 ? throw new


DivideByZeroException("Cannot divide by zero.") : a / b;

public static void Main()


{
var calc = new Calculator();
var menuOptions = new[] { "1. Add", "2. Subtract", "3. Multiply", "4. Divide", "5.
View History", "6. Exit" };

while (true)
{
Console.WriteLine("\nSelect an option:");
Array.ForEach(menuOptions, Console.WriteLine);

Console.Write("Your choice: ");


string choice = Console.ReadLine() ?? "";

if (choice == "6")
{
Console.WriteLine("Exiting...");
break;
}

if (choice == "5")
{
Console.WriteLine("Calculation History :");
int count = Math.Min(calc.history.Length, calc.historyIndex);

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


{
Console.WriteLine($"Result {i + 1}: {calc[i]}");
}
continue;
}
Console.Write("Enter first number: ");
string input1 = Console.ReadLine() ?? "";

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


string input2 = Console.ReadLine() ?? "";

try
{
double result;
if (int.TryParse(input1, out int intNum1) && int.TryParse(input2, out int
intNum2))
{
result = choice switch
{
"1" => Add(intNum1, intNum2),
"2" => Subtract(intNum1, intNum2),
"3" => Multiply(intNum1, intNum2),
"4" => Divide(intNum1, intNum2),
_ => throw new Exception("Invalid choice.")
};
}

else if (double.TryParse(input1, out double doubleNum1) &&


double.TryParse(input2, out double doubleNum2))
{
result = choice switch

{
"1" => Add(doubleNum1, doubleNum2),
"2" => Subtract(doubleNum1, doubleNum2),
"3" => Multiply(doubleNum1, doubleNum2),
"4" => Divide(doubleNum1, doubleNum2),
_ => throw new Exception("Invalid choice.")
};

}
else
{
throw new Exception("Invalid input.");
}

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

calc.StoreResult(result);
}

catch (Exception ex)


{
Console.WriteLine(ex.Message);
}
}
}
}
}
OUTPUT:

Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 1
Enter first number: 23
Enter second number: 56
Result: 79

Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 2
Enter first number: 56
Enter second number: 78
Result: -22

Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 3
Enter first number: 3
Enter second number: 71
Result: 213
Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 4
Enter first number: 45
Enter second number: 3
Result: 15

Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 5
Calculation History :
Result 1: 79
Result 2: -22
Result 3: 213
Result 4: 15

Select an option:
1. Add
2. Subtract
3. Multiply
4. Divide
5. View History
6. Exit

Your choice: 6
Exiting...
PROGRAM 4:
using System;

namespace AreaOfShapes
{
public abstract class Shape
{
public abstract double Area { get; }

public virtual void GetDimensions() { }

public virtual void DisplayInfo()


{
Console.WriteLine($"\nShape: {GetType().Name}");
Console.WriteLine($"Area: {Area:F2}");
}
}

public class Rectangle : Shape


{
public double Length { get; set; }
public double Width { get; set; }

public override double Area => Length * Width;

public override void GetDimensions()


{
Console.Write("Enter length of the rectangle: ");
Length = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter width of the rectangle: ");


Width = Convert.ToDouble(Console.ReadLine());
}

public override void DisplayInfo()


{
base.DisplayInfo();
Console.WriteLine($"Length: {Length}");
Console.WriteLine($"Width: {Width}");
}
}
public class Circle : Shape
{
public double Radius { get; set; }

public override double Area => Math.PI * Radius * Radius;

public override void GetDimensions()


{
Console.Write("Enter radius of the circle: ");
Radius = Convert.ToDouble(Console.ReadLine());
}

public override void DisplayInfo()


{
base.DisplayInfo();
Console.WriteLine($"Radius: {Radius}");
}
}

public class Triangle : Shape


{
public double Base { get; set; }
public double Height { get; set; }

public override double Area => 0.5 * Base * Height;

public override void GetDimensions()


{
Console.Write("Enter base of the triangle: ");
Base = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter height of the triangle: ");


Height = Convert.ToDouble(Console.ReadLine());
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Base: {Base}");
Console.WriteLine($"Height: {Height}");
}
}

public class ShapeCalculator


{
public static void Main()
{
while (true)
{
Console.WriteLine("\n=== SHAPE AREA CALCULATOR ===");
Console.WriteLine("1. Rectangle");
Console.WriteLine("2. Circle");
Console.WriteLine("3. Triangle");
Console.WriteLine("4. Exit");
Console.Write("Choose an option: ");

if (!int.TryParse(Console.ReadLine(), out int choice) || choice < 1 || choice > 4)


{
Console.WriteLine("Invalid choice! Please enter a number between 1 and 4.");
continue;
}

if (choice == 4)
{
Console.WriteLine("Exiting program...");
break;
}
Shape shape = choice switch
{
1 => new Rectangle(),
2 => new Circle(),
3 => new Triangle(),
_ => throw new InvalidOperationException("Invalid shape selection.")
};

shape.GetDimensions();

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


shape.DisplayInfo();
}
}
}
}
OUTPUT:

=== SHAPE AREA CALCULATOR ===


1. Rectangle
2. Circle
3. Triangle
4. Exit
Choose an option: 1
Enter length of the rectangle: 20
Enter width of the rectangle: 50

--- Shape Details ---

Shape: Rectangle
Area: 1000.00
Length: 20
Width: 50

=== SHAPE AREA CALCULATOR ===


1. Rectangle
2. Circle
3. Triangle
4. Exit
Choose an option: 2
Enter radius of the circle: 45

--- Shape Details ---

Shape: Circle
Area: 6361.73
Radius: 45
=== SHAPE AREA CALCULATOR ===
1. Rectangle
2. Circle
3. Triangle
4. Exit
Choose an option: 3
Enter base of the triangle: 20
Enter height of the triangle: 45

--- Shape Details ---

Shape: Triangle
Area: 450.00
Base: 20
Height: 45

=== SHAPE AREA CALCULATOR ===


1. Rectangle
2. Circle
3. Triangle
4. Exit
Choose an option: 4
Exiting program...
PROGRAM 5:
using System;
using System.Globalization;

namespace EmployeeLeaveApp
{
class Program
{
public delegate void LeaveDelegate(int empNo, string empName, DateTime fromDate,
DateTime toDate);
public delegate void DisplayDelegate(int empNo, string empName, DateTime fromDate,
DateTime toDate, string status, string reason, int totalDays);

public static void ProcessLeave(int empNo, string empName, DateTime fromDate,


DateTime toDate)
{
DateTime today = DateTime.Today;
int totalDays = (toDate - fromDate).Days + 1;
int daysNotice = (fromDate - today).Days;
string status = "Leave Sanctioned";
string reason = "";

if (fromDate < today || toDate < today)


{
reason = "Leave cannot be applied for past dates.";
status = "Not Sanctioned";
}
else if (toDate < fromDate)
{
reason = "'To' date cannot be earlier than 'From' date.";
status = "Not Sanctioned";
}
else if (totalDays > 10)
{
reason = $"Leave duration exceeds 10 days. Requested: {totalDays} days.";
status = "Not Sanctioned";
}
else if (totalDays > 4 && daysNotice < 7)
{
reason = "Leave longer than 4 days requires 7 days advance notice.";
status = "Not Sanctioned";
}
else if (totalDays <= 4 && daysNotice < 2)
{
reason = "Short leave requires at least 2 days advance notice.";
status = "Not Sanctioned";
}

// Call display delegate to show the summary


DisplayDelegate displayDel = DisplaySummary;
displayDel(empNo, empName, fromDate, toDate, status, reason, totalDays);
}

public static void DisplaySummary(int empNo, string empName, DateTime fromDate,


DateTime toDate, string status, string reason, int totalDays)
{
Console.WriteLine("\n--- Leave Application Summary ---");
Console.WriteLine($"Application Date : {DateTime.Today:dd-MM-yyyy}");
Console.WriteLine($"Employee Number : {empNo}");
Console.WriteLine($"Employee Name : {empName}");
Console.WriteLine($"Leave From : {fromDate:dd-MM-yyyy}");
Console.WriteLine($"Leave To : {toDate:dd-MM-yyyy}");
Console.WriteLine($"Leave Duration : {totalDays} day(s)");
if (!string.IsNullOrEmpty(reason)) Console.WriteLine($"Reason : {reason}");
Console.WriteLine($"Status : {status}");
}

static int ReadInt(string prompt)


{
int result;
while (true)
{
Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out result)) return result;
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
static string ReadName(string prompt)
{
string? input;
while (true)
{
Console.Write(prompt);
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input) && IsOnlyLetters(input))
return input;
Console.WriteLine("Invalid name. Please enter letters only.");
}
}

static bool IsOnlyLetters(string str)


{
foreach (char c in str)
{
if (!char.IsLetter(c) && c != ' ') return false;
}
return true;
}

static DateTime ReadDate(string prompt)


{
DateTime date;
while (true)
{
Console.Write(prompt);
string? input = Console.ReadLine();
if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
return date;
Console.WriteLine("Invalid date format. Please use dd-MM-yyyy.");
}
}
static void Main()
{
Console.WriteLine("=== Employee Leave Application ===");
LeaveDelegate leaveDel = ProcessLeave;
string? choice;
do
{
int empNo = ReadInt("Enter Employee Number: ");
string empName = ReadName("Enter Employee Name: ");
DateTime fromDate = ReadDate("Enter Leave From Date (dd-MM-yyyy): ");
DateTime toDate = ReadDate("Enter Leave To Date (dd-MM-yyyy): ");

leaveDel(empNo, empName, fromDate, toDate);

Console.Write("\nDo you want to process another leave application? (yes/no): ");


choice = Console.ReadLine()?.Trim().ToLower();
} while (choice == "yes" || choice == "y");

Console.WriteLine("\nThank you for using the Employee Leave Application


System!");
}
}
}
OUTPUT:

=== Employee Leave Application ===


Enter Employee Number: 111
Enter Employee Name: Paul
Enter Leave From Date (dd-MM-yyyy): 27-04-2025
Enter Leave To Date (dd-MM-yyyy): 30-04-2025

--- Leave Application Summary ---


Application Date : 20-04-2025
Employee Number : 111
Employee Name : Paul
Leave From : 27-04-2025
Leave To : 30-04-2025
Leave Duration : 4 day(s)
Status : Leave Sanctioned

Do you want to process another leave application? (yes/no): yes


Enter Employee Number: 112
Enter Employee Name: John
Enter Leave From Date (dd-MM-yyyy): 01-05-2025
Enter Leave To Date (dd-MM-yyyy): 12-05-2025

--- Leave Application Summary ---


Application Date : 20-04-2025
Employee Number : 112
Employee Name : John
Leave From : 01-05-2025
Leave To : 12-05-2025
Leave Duration : 12 day(s)
Reason : Leave duration exceeds 10 days. Requested: 12 days.
Status : Not Sanctioned

Do you want to process another leave application? (yes/no): no

Thank you for using the Employee Leave Application System!


PROGRAM 6:
using System;

// Custom exception for attendance issues


public class AttendanceShortageException : Exception
{
public AttendanceShortageException(string message) : base(message) { }
}

// Custom exception for invalid range


public class AttendanceOutOfRangeException : Exception
{
public AttendanceOutOfRangeException(string message) : base(message) { }
}

class Student
{
public string name;
public int attendancePercentage;

public Student(string n, int a)


{
name = n;
attendancePercentage = a;
}

public void CheckEligibility()


{
if (attendancePercentage < 75)
{
throw new AttendanceShortageException("Attendance is only " +
attendancePercentage + "%. Not eligible to write the exam.");
}
else
{
Console.WriteLine(name + " is eligible to write the examination.");
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter student name: ");
string? nameInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(nameInput))
{
throw new ArgumentException("Name cannot be empty.");
}

string name = nameInput;

Console.Write("Enter attendance percentage (0 to 100): ");


int attendance = Convert.ToInt32(Console.ReadLine());

if (attendance < 0 || attendance > 100)


{
throw new AttendanceOutOfRangeException("Attendance must be between 0 and
100.");
}

Student s = new Student(name, attendance);


s.CheckEligibility();
}
catch (AttendanceOutOfRangeException ex)
{
Console.WriteLine("Invalid Attendance: " + ex.Message);
}
catch (AttendanceShortageException ex)
{
Console.WriteLine("Eligibility Check Failed: " + ex.Message);
}
catch (ArgumentException ex)
{
Console.WriteLine("Input Error: " + ex.Message);
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid number for attendance.");
}
catch (Exception ex)
{
Console.WriteLine("Unexpected error: " + ex.Message);
}

Console.WriteLine("\nPress any key to exit...");


Console.ReadKey();
}
}
OUTPUT:

Enter student name: Paul

Enter attendance percentage (0 to 100): 45

Eligibility Check Failed: Attendance is only 45%. Not eligible to write the exam.

Press any key to exit...


PROGRAM 7:
using System;
using System.Threading;
namespace Thread_Test
{
class TestLock
{
public static int balance { get; set; }
public static readonly Object myLock = new Object();
public void Withdraw(int amount)
{
lock (myLock)
{
if (balance >= amount)
{
Console.WriteLine("\nBalance Before withdrawal: " + balance);
Console.WriteLine("Withdraw:" + amount);
balance -= amount;
Console.WriteLine("Balance After Withdrawal:" + balance);
}
else
{
Console.WriteLine("\nCan\'t Process your transaction, Current Balance is : " +
balance + "and your withdraw amount is:" + amount);
}
}
}
public void WithdrawAmount()
{
Random random = new Random();
Withdraw(random.Next(1, 9) * 1000);
}
public void Deposit(int amount)
{
lock (myLock)
{
Console.WriteLine("\nBalance Before Deposit: " + balance);
Console.WriteLine("Deposit:" + amount);
balance += amount;
Console.WriteLine("Balance After Deposit:" + balance);
}
}

public void DepositAmount()


{
Random random = new Random();
Deposit(random.Next(1, 9) * 1000);
}
}
internal class Program
{
public static void TestThreading()
{
Thread[] withdrawThreads = new Thread[5];
Thread[] depositThreads = new Thread[5];

TestLock.balance = 50000;
Console.WriteLine("\n ==== Withdraw ==== ");

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


{
TestLock t1 = new TestLock();
Thread t = new Thread(new ThreadStart(t1.WithdrawAmount));
withdrawThreads[i] = t;
}
for (int i = 0; i < 5; i++)
{
withdrawThreads[i].Start();
}
for (int i = 0; i < 5; i++)
{
withdrawThreads[i].Join(); // Wait for all withdraw threads to complete
}
Console.WriteLine("\n ==== Deposit ==== ");

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


{
TestLock t2 = new TestLock();
Thread th = new Thread(new ThreadStart(t2.DepositAmount));
depositThreads[i] = th;
}
for (int i = 0; i < 5; i++)
{
depositThreads[i].Start();
}

Console.ReadKey();
}

static void Main(string[] args)


{
TestThreading();
}
}
}
OUTPUT:

==== Withdraw ====

Balance Before withdrawal: 50000

Withdraw:4000

Balance After Withdrawal:46000

Balance Before withdrawal: 46000

Withdraw:7000

Balance After Withdrawal:39000

Balance Before withdrawal: 39000

Withdraw:7000

Balance After Withdrawal:32000

Balance Before withdrawal: 32000

Withdraw:3000

Balance After Withdrawal:29000

Balance Before withdrawal: 29000

Withdraw:3000

Balance After Withdrawal:26000


==== Deposit ====

Balance Before Deposit: 26000

Deposit:3000

Balance After Deposit:29000

Balance Before Deposit: 29000

Deposit:3000

Balance After Deposit:32000

Balance Before Deposit: 32000

Deposit:3000

Balance After Deposit:35000

Balance Before Deposit: 35000

Deposit:2000

Balance After Deposit:37000

Balance Before Deposit: 37000

Deposit:7000

Balance After Deposit:44000


PROGRAM 8:
using System;

namespace ComplexNumberAddition
{
class Complex
{
private double real;
private double imaginary;

public Complex(double real, double imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

// Overload + operator to add two Complex objects


public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

// Override ToString() for displaying complex number


public override string ToString()
{
return $"{real} + {imaginary}i";
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the first complex number:");
Console.Write("Real part: ");
double r1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Imaginary part: ");
double i1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\nEnter the second complex number:");
Console.Write("Real part: ");
double r2 = Convert.ToDouble(Console.ReadLine());
Console.Write("Imaginary part: ");
double i2 = Convert.ToDouble(Console.ReadLine());

Complex c1 = new Complex(r1, i1);


Complex c2 = new Complex(r2, i2);

Complex sum = c1 + c2;

Console.WriteLine($"\nSum of the complex numbers: {sum}");


}
}
}
OUTPUT:

Enter the first complex number:

Real part: 4

Imaginary part: 5

Enter the second complex number:

Real part: 12

Imaginary part: 7

Sum of the complex numbers: 16 + 12i


PROGRAM 9:
using System;
namespace UnaryOperator
{
class Calculator
{
public int number1, number2;
public Calculator(int num1, int num2)
{
number1 = num1;
number2 = num2;
}
public static Calculator operator --(Calculator c1)
{
c1.number1 = c1.number1-2;
c1.number2 = c1.number2-2;
return c1;
}
public static Calculator operator ++(Calculator c2)
{
c2.number1 = c2.number1 + 2;
c2.number2 = c2.number2 + 2;
return c2;
}
public void Print()
{
Console.WriteLine("Number1=" + number1);
Console.WriteLine("Number2=" + number2);
}
}
internal class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator(15, -25);
Calculator calc1 = calc;

calc = --calc;
calc.Print();

Console.WriteLine();

calc1 = ++calc;
calc.Print();
Console.ReadKey();
}
}
}
OUTPUT:

Number1=13

Number2=-27

Number1=15

Number2=-25

You might also like