While loop not working

Good Day. I'm having some trouble trying to figure out why the loop is not working correctly. I've looked at and compared to several similar programs, and I'm just not seeing it. Any suggestions or hints on what I need to look for would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
int main ()
{
    //Local constants
    int SENTINEL = 999;
    int MIN = 0;
    int MAX = 100;

    //Local variables
    int grade;
    int total = 0;
    int count = 0;
    float average;

    /********************Begin main Function Executables***********************/

    //Repeatedly ask user for grade until sentinel value (999) is reached

    cout << "please enter grade value 0-100  ( " << SENTINEL <<  " to quit)  "   ;
    cin >> grade;
	
	while (grade != SENTINEL)
		{
			if (grade >= MIN && grade <= MAX) 
					{
						total += grade;
						count ++;
					}
			if (grade != SENTINEL)
					{
						cout << "Invalid data. Must be  " << MIN << "to  " << 
						MAX << endl;
					}
		}

    //Calculate the average
    average = float (total)/float (count);
    

    //Display the average
    cout << "For " << count << " grades, the average is " << average << endl;
    cout << "\n\n";
    

    //Hold execution on screen
    system ("pause");

    //Indicate to OS successful termination of program
    return 0;

}   //End main 
There are two main issues with your while loop:

1) There is no way to break out of the loop. As soon as the user enters in one grade, the program will go into an infinite loop. Perhaps you can place the cin point inside the loop, so the user can enter in more than one grade, including the SENTINEL option. Of course, this means that you have to initialize grade beforehand.

2) The second if condition inside the while loop is pointless. The loop only iterates if grade != SENTINEL, so that condition will always be true inside the loop. Therefore, "Invalid data. Must be..." will always print on the screen. Use else instead of if(grade != SENTINEL).
Topic archived. No new replies allowed.