You are using a version without Ads of this website. Please, consider donating:

### Do While loop trouble

closed account (Ebf21hU5)
I've written a program that acts as a Math Tutor and I want to make it so that the user has 5 attempts to get the question right. I want to use a do while loop but I'm having trouble making it 5 attempts so far it only gives the user 1 attempt. Here's what I have so far. Any suggestions to make it better will be greatly appreciated.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` ``````#include #include using namespace std; int main() { int rnum1 = (rand()%100)+1; int rnum2 = (rand()%100)+1; int stdntAns; int NumOfAttempts = 0; cout << "Welcome to Math Tutor" << endl; cout << "This program will present you with two random numbers that you will add together." << endl; cout << "When you're done typing your answer press Enter to see if it's correct." << endl; cout << "Good Luck!" << endl; cout << " " << endl; cout << "What is " << rnum1 << "+" << rnum2 << "= ?" << endl; cin >> stdntAns; { char enter; do { cin.get(enter); } while (enter != '\n'); } do { NumOfAttempts = NumOfAttempts + 1; } while (NumOfAttempts <= 5); { if (stdntAns == (rnum1+rnum2)) { cout << "Congrats! That is the correct answer." << endl; } else if (stdntAns != (rnum1+rnum2)) { cout << "That answer is incorrect. Please try again." << endl; cin >> stdntAns; } else { cout << "You have reached your limit of guesses." << endl; } } system ("pause>nul"); return 0; }``````
This
 ``12345`` `````` do { NumOfAttempts = NumOfAttempts + 1; } while (NumOfAttempts <= 5);``````
does nothing more than increasing the variable `NumOfAttempts`

your can use a `for` loop like so:
 ``12345678910111213141516171819`` `````` int NumOfAttempts = 0; for(; NumOfAttempts < 5; NumOfAttempts = NumOfAttempts + 1) { if (stdntAns == (rnum1+rnum2)) { cout << "Congrats! That is the correct answer." << endl; break; // Note: this will end the loop } else if (stdntAns != (rnum1+rnum2)) { cout << "That answer is incorrect. Please try again." << endl; cin >> stdntAns; } } if(NumOfAttempts >= 5) { cout << "You have reached your limit of guesses." << endl; }``````
closed account (Ebf21hU5)
Ok that makes perfect since. Thanks for your help!
Topic archived. No new replies allowed.