In C programming, structures are used to group related variables under one name. This blog post will guide you on how to define a structure called struct personal
that stores a person’s name, date of joining, and salary — and how to use it to read and print information of 5 people.
What is struct personal
?
You can define a structure to hold employee data like this:
struct personal {
char name[50];
char dateOfJoining[20];
float salary;
};
Objective
- Define a structure named
struct personal
- Members:
- Name (string)
- Date of Joining (string)
- Salary (float)
- Input and store data for 5 persons
- Print the data on the screen
C Program Example
#include <stdio.h>
#define SIZE 5
// Define structure
struct personal {
char name[50];
char dateOfJoining[20];
float salary;
};
int main() {
struct personal employees[SIZE];
// Reading data
for (int i = 0; i < SIZE; i++) {
printf("\nEnter details for Person %d:\n", i + 1);
printf("Name: ");
scanf("%s", employees[i].name);
printf("Date of Joining (DD-MM-YYYY): ");
scanf("%s", employees[i].dateOfJoining);
printf("Salary: ");
scanf("%f", &employees[i].salary);
}
// Printing data
printf("\n--- Employee Information ---\n");
for (int i = 0; i < SIZE; i++) {
printf("\nPerson %d:\n", i + 1);
printf("Name: %s\n", employees[i].name);
printf("Date of Joining: %s\n", employees[i].dateOfJoining);
printf("Salary: %.2f\n", employees[i].salary);
}
return 0;
}
Sample Output
Enter details for Person 1:
Name: Ravi
Date of Joining: 01-06-2020
Salary: 35000
...
--- Employee Information ---
Person 1:
Name: Ravi
Date of Joining: 01-06-2020
Salary: 35000.00
Key Concepts Covered
- Using arrays of structures.
- Reading strings and floats using
scanf
. - Grouping data for real-world scenarios.
Tips
- Use
fgets()
for full names with spaces instead ofscanf("%s", ...)
. - For date operations, consider using nested structures or date parsing in advanced programs.
Conclusion
This program is a great example of how to use structures in C to handle multiple records efficiently. By using an array of struct personal
, you can manage and display employee information cleanly and effectively.
Understanding structure usage in C is key to building scalable and modular programs.