/* This is an incomplete program to compute the GPA of a set of courses. gpa.in contains sample input (plain text file) gpa.out contains sample output (plain text file) compile in a Unix shell: gcc gpa.c (creates executable called a.out) run in a Unix shell: ./a.out (input from keyboard, output to screen) run in a Unix shell: ./a.out gpa.out */ // First part of a C program usually contains pre-processor directives: // include header files (contain function prototypes) for used libraries #include // for basic I/O: puts, getchar, printf #include // for character related functions: isspace, isdigit #include // for string functions: // create symbolic constants to avoid "magic numbers" #define GSIZE 3 // function declarations are called prototypes // every function must be declared or fully defined before it is called double getpoints(char []); // no parameter names are needed int main(void) { char grade[GSIZE]; int i, ch; int credits; double points; double totalpoints = 0, totalcredits = 0; puts("enter grades and credits: "); // repeat until end of input while ((ch = getchar()) != EOF) { // get grade i = 0; while (!isspace(ch)) { grade[i++] = ch; ch = getchar(); } grade[i] = '\0'; // strings must be terminated with special null character points = getpoints(grade); // skip whitespace while (isspace(ch)) { ch = getchar(); } // read credits, one character at a time, build integer credits = 0; while (isdigit(ch)) { credits = credits * 10 + ch - '0'; ch = getchar(); } // go to next line while (ch != '\n') ch = getchar(); printf("grade is: %-2s credits = %d points = %4.1f \n", grade, credits, points); // missing parts to actually use the grade to compute the GPA! } // while not EOF return 0; // 0 indicates normal termination, no errors } // main /* Converts a letter grade to its corresponding point value. */ double getpoints(char g[]) { double points = 0; g[0] = toupper(g[0]); switch (g[0]) { case 'A': points = 4; break; case 'B': points = 3; break; case 'C': points = 2; break; case 'D': points = 1; break; default: points = 0; } if (g[1] == '+' && 'B' <= g[0] && g[0] <= 'D') points += .3; if (g[1] == '-' && 'A' <= g[0] && g[0] <= 'C') points -= .3; return points; }