Why didn't the counter drop to 0 or negative values?

The program is working absolutely fine.

However the question I'm about to ask just keeps bugging me.

Say if I input any other values other than 1 or 2, the studentCounter is suppose to minus 1.

After I input 1 and 2 up to 9 times, I purposely enter other values to see if the value of studentCounter will be reduced to like...0 or negative values.

Which it doesn't although I enter other values like 10 times.

If I enter 1 or 2 after correctly input 9 times, the console considers my input the 10th time.

So why didn't the studentCounter drop to 0 or negative values??

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
  #include <iostream>

using namespace std;

int main()
{
	int passes = 0; //number of passes
	int failures = 0; //number of failures
	int studentCounter = 1; //student counter
	int result; //one exam result (1 = pass, 2 = fail)

	//process 10 students using counter-controlled loop
	while ( studentCounter <= 10 )
	{
		//prompt user to input test result
		cout << "Enter result (1 = pass, 2 = fail): " << endl;
		cin >> result; //input result

		if ( result == 1 )		
			passes = passes + 1;
		else if
			( result == 2 )
			failures = failures + 1;
		else 
			{				
				cout << "invalid input. Please insert 1 or 2 only!" << endl;
				studentCounter = studentCounter - 1;
			}//end else

			studentCounter = studentCounter + 1;
	}//end while

	//termination phase; display number of passes and failures

	cout << "Passes: " << passes << "\nFailures: " << failures << endl;

	//determine whether more than 8 students pass
	if (passes > 8)
		cout << "Bonus to instructor\n";
}//end main 
cuz you decrement it AND THEN increment it again.
also, you never check to see if your counter is < zero.

you while loop could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
while (studentCounter>=0 && studentCounter <= 10 )
	{
		//prompt user to input test result
		cout << "Enter result (1 = pass, 2 = fail): " << endl;
		cin >> result; //input result

		if ( result == 1 )
		{
			passes = passes + 1;
			studentCounter++;
		}
		else if	( result == 2 )
		{
			failures = failures + 1;
			studentCounter++;
		}
		else 
		{				
			cout << "invalid input. Please insert 1 or 2 only!" << endl;
			studentCounter--;
		}//end else
	}//end while 
Last edited on
ahhhhhhhh I see thanks man! You rock!
Topic archived. No new replies allowed.