Code:
#include <stdio.h>
#include <string.h>
struct students
{
char name[30];
int grade[5];
} student[300];
void get_info(struct students student[], int *num_students, int *exams);
void print_names(struct students student[], int num_students);
void sort_names(struct students student[], int num_students, int exams);
int main()
{
int num_students, exams, option;
get_info(student, &num_students, &exams);
sort_names(student, num_students, exams);
do
{
printf("Enter 1 to continue the program. Enter 0 to terminate the program.\n");
scanf("%d", &option);
if(option == 0){
printf("\nGoodbye!");
return 0;
}
print_names(student, num_students);
}while(option != 0);
printf("\nGoodbye!");
return 0;
}
void get_info(struct students student[], int *num_students, int *exams)
{
int i, j, grades = 0;
char l_name[30], f_name[30], file[40];
FILE *infile;
/* Get file name */
printf("Enter the name of the file containing the grades: ");
scanf("%s", file);
/* Open file and read in info */
infile = fopen(file, "r");
fscanf(infile, "%d %d", num_students, exams);
for(i = 0; i < *num_students; i++)
{
fscanf(infile, "%s %s", l_name, f_name);
strcat(l_name, " ");
strcat(l_name, f_name);
strcpy(student[i].name, l_name);
for(j = 0; j < *exams; j++)
{
fscanf(infile, "%d", &grades);
student[i].grade[j] = grades;
}
}
/* Close file */
fclose(infile);
}
void sort_names(struct students student[], int num_students, int exams)
{
int i, count = 0;
char temp_name[30];
do
{
for(i = 0; i < num_students; i++)
{
if(strcmp(student[i].name, student[i+1].name) > 0)
{
strcpy(temp_name, student[i].name);
strcpy(student[i].name, student[i+1].name);
strcpy(student[i+1].name, temp_name);
}
}
count++;
}while(count < num_students);
}
void print_names(struct students student[], int num_students)
{
int i;
printf("\nHere is the sorted list: \n");
for(i = 0; i < num_students; i++)
{
if(i + 1 < 10)
printf("%d. %s\n", i + 1, student[i].name);
else if(i + 1 >= 10 && i + 1 < 100)
printf("%d. %s\n", i + 1, student[i].name);
else if(i + 1 >= 100)
printf("%d. %s\n", i + 1, student[i].name);
}
}