RLuck
RLuck

Reputation: 93

Creating a gradebook program in C

I'm working on a program that will keep track of grades entered. The program should ask if the user is finished inputting grades. If the the user is not finished, the user will continue to enter grades. If the user is finished, program will print the grades. Every time I run the program, it crashes.

Here's what I got.

#include <stdio.h>

int main (){
    int i = 0;
    float gradeBook;
    char ans, y, Y, n, N;

    printf("Please enter grade %d: ", i + 1);
    scanf("%.2f", &gradeBook);

    printf("\nDo you have more grades to enter? [Y or N] ");
    scanf("%c", ans);

    while(ans == 'y' || ans == 'Y'){
        printf("Please enter the next grade %d: ", i + 1);
        scanf("%i", &gradeBook);

        printf("\nDo you have more grades to enter? ");
        scanf("%c", ans);
    }
    printf("You have entered %d grades", i);
    printf("The grades you have entered are %.2f ", gradeBook);
    return 0;
}

Upvotes: 0

Views: 1518

Answers (2)

jmds
jmds

Reputation: 96

Your program crashes because you are missing the & in ans in your scanf. Without the &, the scanf treats the value in "ans" as an address, and will try to access it, thus seg fault.

PS: In each iteration you are overwriting the value in "gradeBook", if you want to print a set of values, you should use an array.

Upvotes: 1

evandro10
evandro10

Reputation: 132

You should use arrays for problems like this. Here is what I did:

#include <stdio.h>

int main (){
int i = 0, j;
float gradeBook[20];
char ans;

printf("Please enter grade %d: ", i + 1);
scanf("%f", &gradeBook[0]);

printf("\nDo you have more grades to enter? [Y or N] \n");
scanf(" %c", &ans);

while (ans == 'y' || ans == 'Y') {
printf("Please enter the next grade: \n");
i += 1;
scanf("%f", &gradeBook[i]);

printf("\nDo you have more grades to enter? \n");
scanf(" %c", &ans);
}

printf("You have entered %d grades\n", i+1);
printf("The grades you have entered are: \n");
for (j=0; j<=i; j++)
printf("%.2f ", gradeBook[j]);

printf("\n\n");

return 0;
}

Upvotes: 2

Related Questions