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

The program is working absolutely fine.

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??

 ``12345678910111213141516171819202122232425262728293031323334353637383940`` `````` #include 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:
 ``12345678910111213141516171819202122`` ``````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.