GPA Calculator in C

346 views Asked by At

I'm trying to get this code to calculate a class's average GPA. The problem I'm having is that I seem to have made a mistake in my do...while code, because, when I run it, it constantly loops back to asking me to input another GPA, rather than asking if I want to calculate the average or not.

#include<stdio.h>

int main()
{
    float faGPA[30], fSum = 0, fAvg = 0;
    int x, y;
    char cResp = '\0';

    printf("\t\tGPA Calculator\n");
    printf("\nEnter up to 30 GPAs into the calculator.\n");

    do{
        printf("\nEnter a GPA: ");
        scanf("%f", &faGPA[x]);
        x++;
        printf("\nCalculate the GPA average (Y/N)?\n");
        scanf("%c", &cResp);
    } while(x < 30 && cResp != 'Y' || x < 30 && cResp != 'y');

    for(y = 0; y < (x + 1); y++)

    fSum += faGPA[y];
    fAvg = (fSum / (y - 1));

printf("\nThe class GPA is:%.2f", fAvg);

return 0;
}
2

There are 2 answers

3
jllama On BEST ANSWER

There are two issues here. First, you need to discard new lines on your scanf. See here for details.

Second the || operator is going to cause the whole statement to evaluate to true no matter if the user has entered Y or y. Try switching to an && operator and closing the two checks in their own parenthesis.

See sample below - it should at least get you further, though I'm still not getting the right answer from you math.

float faGPA[30], fSum = 0, fAvg = 0;
int x = 0, y = 0;
char cResp = '\0';

printf("\t\tGPA Calculator\n");
printf("\nEnter up to 30 GPAs into the calculator.\n");

do{
    printf("\nEnter a GPA: ");
    scanf("%f", &faGPA[x]);
    x++;
    printf("\nCalculate the GPA average (Y/N)?\n");
    scanf("\n%c", &cResp);
} while (x < 30 && (cResp != 'Y' && cResp != 'y'));

for (y = 0; y < (x + 1); y++)

    fSum += faGPA[y];
fAvg = (fSum / (y - 1));

printf("\nThe class GPA is:%.2f", fAvg);

return 0;
0
Zarocross On

Your logic in the check at the bottom is a little off.

It should be 'end if you said Y or y or if the class size has hit 30.

This translates to:

while(x < 30 || cResp != 'y' || cResp != 'Y')