In this tutorial, we will learn how to write a C program to read and print employee details using structures.
C Program for employee details using structure
#include <stdio.h>
// Define the structure for employee details
struct Employee {
int id; // Employee ID
char name[50]; // Employee Name
float salary; // Employee Salary
};
int main() {
// Declare a variable of type struct Employee
struct Employee emp;
// Prompt the user to enter the employee's ID and store it in emp.id
printf("Enter Employee ID: ");
scanf("%d", &emp.id);
// Prompt the user to enter the employee's name and store it in emp.name
// Note: %s reads a string until a space or newline is encountered
printf("Enter Employee Name: ");
scanf("%s", emp.name);
// Prompt the user to enter the employee's salary and store it in emp.salary
printf("Enter Employee Salary: ");
scanf("%f", &emp.salary);
// Display the employee's details
printf("\nEmployee Details:\n");
// Print the employee's ID
printf("ID: %d\n", emp.id);
// Print the employee's name
printf("Name: %s\n", emp.name);
// Print the employee's salary
printf("Salary: %.2f\n", emp.salary);
// Indicate that the program ended successfully
return 0;
}
How this program works?
- Include Header File:
#include <stdio.h>
This line includes the standard input-output library in our C program, which is required for usingprintf()
andscanf()
functions. - Structure Definition:
struct Employee {
This defines a structure named
int id;
char name[50];
float salary;
};Employee
which contains three fields: an integerid
, a character arrayname
(to hold the employee’s name), and a floatsalary
. This is to store the employee details so that we can later fetch the details from it and print it. - Main Function:
int main() {
This declares a variable
struct Employee emp;emp
of typestruct Employee
. This variable emp refers to the structure so we can use it to access structure for reading and writing data into it. - Taking Input:
printf("Enter Employee ID: ");
Here
scanf("%d", &emp.id);
printf("Enter Employee Name: ");
scanf("%s", emp.name);
printf("Enter Employee Salary: ");
scanf("%f", &emp.salary);printf
statements are prompts to the users asking for input andscanf
statements store the user input into the structure usingemp
. - Displaying Details:
printf("\nEmployee Details:\n");
These lines print the employee’s details stored in the structure using
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("Salary: %.2f\n", emp.salary);emp
variable.
Leave a Reply