Please fullfill each of the required parts of this program. Write a program that
ID: 3566616 • Letter: P
Question
Please fullfill each of the required parts of this program.
Write a program that would allow a user to enter student names and Final grades (e.g. A,B,C,D,F) from their courses. You do not know how many students need to be entered. You also do not know how many courses each of the students completed. Design your program to calculate the Grade Point Average (GPA) for each student based on each of their final grades. The program should output the Student name along with the GPA.
There are 5 components of your submission including:
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student student;
typedef struct student {
char *name;
double gpa;
student *next;
} student;
char * prompt( const char * s ) {
char *p, *ln= (char *) malloc( 10000 );
if ( ln == 0 ) return 0;
printf( "%s", s );
if ( fgets( ln, 10000, stdin ) == 0 || (p= strtok( ln, " " )) == 0 ) {
free( ln );
return 0;
}
strcpy( ln, p );
return (char *) realloc( ln, strlen( ln ) + 1 );
}
double gpa( const char *name ) {
int sum= 0, n= 0;
char pr[200], *r;
sprintf( pr, "Enter a grade for %s: ", name );
while ( (r= prompt( pr )) != 0 ) {
int grade= 0;
switch ( *r ) {
case 'A':
case 'a':
++grade;
case 'B':
case 'b':
++grade;
case 'C':
case 'c':
++grade;
case 'D':
case 'd':
++grade;
case 'F':
case 'f':
++grade;
default:
break;
}
if ( grade > 0 )
sum += (grade - 1), ++n;
else
printf( "Error entering grade letter. Re-enter please. " );
free( r );
}
return n > 0? sum / (double) n : -1.0;
}
void printnames( student *head ) {
if ( head != 0 ) {
printnames( head->next );
printf( "%s %.2lf ", head->name, head->gpa < 0.0? 0.0 : head->gpa );
}
}
student * destroynames( student *head ) {
if ( head != 0 ) {
destroynames( head->next );
free( head->name );
free( head );
}
return 0;
}
int main( void ) {
char *name;
student *list= 0;
while ( (name= prompt( "Enter new student name: " )) != 0 ) {
student *node= (student *) malloc( sizeof( student ) );
if ( node == 0 ) { free( name ); break; }
node->name= name;
node->gpa= gpa( name );
node->next= list, list= node;
}
printnames( list );
list= destroynames( list );
return 0;
}