I have to say that this task is a little more complicated than the previous exercises, because it was necessary to use a special function to generate numbers randomly. This program was thought as a game, where the user have to guess a random number. I decided to give the user only five chances to achieve it.
This is my code:
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { int X, c=1; srand(time(NULL)); // random numbers are activated int N = rand()%100+1; // random numbers between 1-100 formula: rand()%(RANGE+1)+MINIMUM cout << "Let's play a game! \nYou have to guess the number I have in mind, but you only have 5 chances \nI'll give you a clue: the number is between 1 and 100" << endl; cout << "What number am I thinking? "; cin >> X; while (X!=N && c<5) { if (X>N) { cout << "Sorry but " << X << " is too high. \nYou have " << 5-c << " attempts remaining.\nTry again: "; cin >> X; } else if (X<N) { cout << "Sorry but " << X << " is too low. \nYou have " << 5-c << " attempts remaining.\nTry again: "; cin >> X; } c++; } if (X==N) { cout << "Congratulations winner! You have guessed my secret number" << endl; } else { cout << "You lost! \nThe number I was thinking about is " << N << " \nGood luck for the next time."<<endl; } return 0; }
As you can see, I included a library call stdlib.h and time.h (that are necessary for generating random numbers).
I used conditionals to evaluate if the user entered the right value or have to try again, and a loop (a “while” specifically) with the purpose of repeating the procedure only five times if the user doesn’t guess the number.