Enter and print details of n employees using structures and dynamic memory allocation
This
program is used to show the most basic use of structures. The structure
is made of a character array name[], integer age and float salary.
We’ll make an array of the structure for the employees. We’ll also use
dynamic memory allocation using malloc. You can also use a linked list
to the same which is a better option. Let’s check the code.
|
#include
#include
typedef struct {
char name[30];
int age;
float salary;
}emp;
int main(){
int n,i;
emp *employee;
printf ( "Enter no of employees: " );
scanf ( "%d" ,&n);
employee=(emp*) malloc (n* sizeof (emp));
for (i=0;i<n;i++){
printf ( "\n\nEnter details of employee %d\n" ,i+1);
printf ( "Enter name: " );
scanf ( "%s" ,employee[i].name);
printf ( "Enter age: " );
scanf ( "%d" ,&employee[i].age);
printf ( "Enter salary: " );
scanf ( "%f" ,&employee[i].salary);
}
printf ( "\nPrinting details of all the employees:\n" );
for (i=0;i<n;i++){
printf ( "\n\nDetails of employee %d\n" ,i+1);
printf ( "\nName: %s" ,employee[i].name);
printf ( "\nAge: %d" ,employee[i].age);
printf ( "\nSalary: %.2f" ,employee[i].salary);
}
getch();
return 0;
}
|