Practical 4
Aim: Write a program to declare a class ‘staff’ having data members as name and post.accept this data 5 for 5 staffs
and display names of staff who are HOD.
Code:
using System;
namespace staff
{
class Staff
{
string name, post;
// Method to get user input for name and post
public void getdata()
{
Console.Write("Enter name: ");
name = Console.ReadLine();
// Loop to ensure post is either "HOD" or "staff"
while (true)
{
Console.Write("Enter post (HOD or staff): ");
post = Console.ReadLine().Trim().ToLower(); // Convert input to lowercase to handle case-insensitivity
// Validate the post
if (post == "hod" || post == "staff")
{
post = post.ToUpper(); // Store the post in uppercase for consistency
break;
}
else
{
Console.WriteLine("Invalid post. Please enter 'HOD' or 'staff'.");
}
}
}
// Method to display staff details+
public void display()
{
Console.WriteLine(name + "\t\t" + post);
}
// Method to return the post of the staff member
public string getPost()
{
return post;
}
}
class Program
{
static void Main(string[] args)
{
// Ask how many staff members are there
Console.Write("Enter the number of staff members: ");
int numStaff = int.Parse(Console.ReadLine());
// Create an array based on the entered number
Staff[] objStaff = new Staff[numStaff];
// Loop through and get data for each staff member
for (int i = 0; i < numStaff; i++)
{
objStaff[i] = new Staff();
Console.WriteLine($"\nEntering details for Staff {i + 1}:");
objStaff[i].getdata();
}
// Display the details of staff members with the post "HOD"
Console.WriteLine("\nName \t\t Post");
for (int i = 0; i < numStaff; i++)
{
if (objStaff[i].getPost() == "HOD")
{
objStaff[i].display();
}
}
}
}
}
Output