Guess Secret Number Game

Hi, I'm very new to coding and can't figure this out. I need the program to have a secret number the user has to guess between 1-10. However, I need the program to stop after 5 tries at guessing (5th try can still work) and display the amount of tries (5) and secret number.

Also, when the number is found, it should display how many tries and the secret number.

I've pasted the last code that worked, the ones I put for tries I removed as I either got an error or it messed it up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdlib>
#include <time.h>
#include <iostream>
 
using namespace std;
 
int main() {
      srand(time(0));
      int number;
      number = rand() % 10 + 1;
      int guess;
      do {
            cout << "Enter your estimate: ";
            cin >> guess;
            if (guess < number)
                  cout << "Your estimate is less than the secret number" << endl;
            else if (guess > number)
                  cout << "Your estimate is more than the secret number" << endl;
            else
                  cout << "Your guess is right!" << endl;
      } while (guess != number);
      system("PAUSE");
      return 0;
}
You'll need a new variable to keep track of how many tries the user has used up so far:
int tries = 0;

Then, within the loop, you'll want to increment the number of tries after each time the user enters a guess:
1
2
3
4
5
++tries;
/* Or any of the following (equivalent) statements:
tries++;
tries += 1;
tries = tries + 1; */

In the condition for your while loop, you'll want to check not only that the user's guess isn't the correct number but also that the user hasn't exceeded his/her maximum number of tries:
while (guess != number && tries < 5);

Afterwards, you'll want to distinguish between whether the user won or if he/she ran out of tries and lost (since either one of those will cause the loop to end):
1
2
3
4
if (guess == number) // If the user actually guessed right
    // Yay, you win.
else // Otherwise, we know that the user ran out of tries
    // You lose, try again 

This is also the spot for displaying the number of tries and the secret number.
Topic archived. No new replies allowed.