Click here to Skip to main content
15,851,242 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create a code that outputs the average of a student's grade. The user inputs a name then three of their exam scores and then the average is outputted. I can't seem to figure out how to let the user input any number of student names. I want the program to terminate when the user does not put in another name but I can't seem to figure it out. The most progress I've gotten without the program resulting in an infinite loop is with an if statement, but the if statement terminates after one entry.
#include <stdio.h>
int main ()
{
  /* variable definition: */
  char StudentName[100];
  float ExamValue, Sum, Avg;
  int exams;
if (StudentName!=0) {
     // reset Sum to 0
     Sum =0.0;
     printf("Enter Student Name \n");
     scanf("%s", StudentName);
     // Nested Loop for Exams
    for (exams=0; exams < 3; exams++)
    {
        printf ("Enter exam grade: \n");
        scanf("%f", &ExamValue);
        Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
} else {
return 0; }
} 


What I have tried:

I've tried to use a while loop so that when the user input is new line it would terminate but that didn't work. I've tried a for loop that started with students = 0; students < StudentName; students++; but that didn't work. The most I've gotten was this if loop, but I'm not understanding why it isn't working. I've tried to use while(StudentName>0) but that results in an infinite loop. I just want the program to stop when the user stops inputting names.
Posted
Updated 7-Sep-17 9:20am
v2

1 solution

Because you do this:
char StudentName[100];

This condition will always pass:
if (StudentName!=0) {
Because StudentName is an array, and in C the name of an array is a pointer to the first element. Pointers are always non-zero when they are valid, so your condition cannot fail.

At the moment, you have one loop - to get three items from the user and average them. To repeat this for a second, or third, or fourth student, you need a second loop around the "get a student name and work out the average" code. Probably, replacing the if line I mentioned above with an appropriate while loop and adding a "do you want another student?" question and response at the bottom of the loop would do what you want - but this is your homework, not mine; so I'll give you no code!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900