C++ Mini Game: Guess the Number

Today, we bring you a mini game: Guess the Number. Compile it quickly and see who can guess the correct number in the fewest attempts!

#include<iostream>#include<cstdlib>  // For rand() and srand()#include<ctime>    // For time()// Bit Rabbit - Informatics Competition Productionusing namespace std;int main() {    int secretNumber, guess, attempts = 0;// Set random seed    srand(time(0));// Generate a random number between 1 and 100    secretNumber = rand() % 100 + 1;    cout << "Welcome to the Guess the Number game!" << endl;    cout << "I have thought of a number between 1 and 100, can you guess it?" << endl;    do {        cout << "Please enter your guess: ";        cin >> guess;        attempts++;  // Record the number of attempts        if (guess > secretNumber) {            cout << "Too high! Try again." << endl;        } else if (guess < secretNumber) {            cout << "Too low! Try again." << endl;        } else {            cout << "Congratulations, you guessed it!" << endl;            cout << "You guessed a total of " << attempts << " times." << endl;        }    } while (guess != secretNumber);        return 0;}

Leave a Comment