Create an employee structure that contains members for the first name, last name
ID: 3676595 • Letter: C
Question
Create an employee structure that contains members for the first name, last name, and salary. Use typedef to make an employee_t data type. Create a function called init_employee() that takes an employee_t variable by reference and puts a random string in its first name member, a random string in its last name member, and a random float in its salary member. Create a print_employee() function that takes an employee variable in by reference and prints out its members. In the main() function, ask the user how many employees to create and dynamically allocate an array for employee_t elements of that size. Use the functions on each element on the array and calculate and display the average salary.
Sample Run:
How many employees? 5
Employee
Name: LDN, VCUSIPQGW
Salary: $85054.53
Employee
Name: GMGCA, GFH
Salary: $47384.86
Employee
Name: ZIPTYDAALC, AQRS
Salary: $14797.11
Employee
Name: VIAKOJQ, KVJVGTU
Salary: $69278.08
Employee
Name: AOQSGKGO, FN
Salary: $32002.21
Average: $49703.36
Explanation / Answer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
typedef struct Employee{
char* first_name;
char* last_name;
double salary;
} employee_t;
char *randstring(int length) {
srand ( time(NULL) );
char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
size_t stringLen = 26*2+10+7;
char *randomString;
randomString = malloc(sizeof(char) * (length +1));
if (!randomString) {
return (char*)0;
}
unsigned int key = 0;
int n;
for ( n = 0;n < length;n++) {
key = rand() % stringLen;
randomString[n] = string[key];
}
randomString[length] = '';
return randomString;
}
employee_t *init_employee(employee_t *emp)
{
srand ( time(NULL) );
emp->first_name = randstring(20);
emp->last_name = randstring(20);
emp->salary = 10000 + rand()% 10000000;
return emp;
}
void print_employee (employee_t *emp)
{
printf("Employee ");
printf("Name: %s, %s ",emp->first_name, emp->last_name );
printf("Salary: $%lf ",emp->salary);
}
int main() {
srand ( time(NULL) );
employee_t *newEmployee, tmp; // newEmployee is now a pointer
int e;
printf("How many employees: ");
scanf("%d",&e);
double *a = (double*)malloc(e*sizeof(double));
int i =0;
while(i<e)
{
newEmployee = init_employee( &tmp ); // newEmployee now points to tmp
a[i] = newEmployee->salary;
print_employee(newEmployee);
i++;
}
double sum = 0;
for (i = 0; i < e; ++i)
{
sum = sum + a[i];
}
printf("Average: %lf ",sum/e);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.