Hi everyone,
I've been working through the loops section of jumping into c++ and made a small 'maths quiz'. I wanted a random number i.e. rand() for numA and numB (1,2,3,4,5,6,7,8,9 or 10) but haven't managed that yet so I set them manually instead for now.
#include <cstdlib> is in there because I read that is needed for rand() to work. Once again, not sure why, includes will come later I expect.
Here's the quiz:
What I wanted to know is whether or not this would be the correct use of the 'break' command. I thought maybe the loop would handle when a game is over or not i.e. after 3 wrong guesses, or a correct answer, cease looping. Adding break in like this seems wrong to me, but of course, not sure why.Code:#include <iostream> #include <cstdlib> using namespace std; int main () { int numA = 5; int numB = 5; int answer = numA + numB; int guess; for ( int attempts = 1; !(guess==answer); attempts++ ) { cout << "What is " << numA << " + " << numB << "? "; cin >> guess; cin.ignore(); if (guess == answer) { cout << "Well done, got it in: " << attempts << " attempts!\n"; break; } else { if ( attempts < 3 ) { cout << "Incorrect. Please try again.\n"; } else { cout << "Sorry, run out of attempts! Game over..."; break; } } } }
Any feedback is more than welcome. Maybe a pointer for a better way of achieving this or what I've done wrong. I'd rather suggestions than solutions, I wont learn anything copying and pasting!
Thanks in advance.
Sam.