Building A Guessing Game

Lesson 21
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

Here’s an example of a guessing game program in C++ using a while loop:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL)); // seed the random number generator with the current time
    int secret_number = rand() % 100 + 1; // generate a random number between 1 and 100
    int guess;
    int tries = 0;

    std::cout << "Guess a number between 1 and 100." << std::endl;

    while (true) {
        std::cin >> guess;
        tries++;

        if (guess == secret_number) {
            std::cout << "Congratulations, you guessed the number in " << tries << " tries!" << std::endl;
            break;
        } else if (guess < secret_number) {
            std::cout << "Too low. Guess again: ";
        } else {
            std::cout << "Too high. Guess again: ";
        }
    }

    return 0;
}

In this example, the program generates a random number between 1 and 100 using the rand() function from the <cstdlib> library, seeded with the current time using srand(). The program then prompts the user to guess the number using std::cout, and reads in the input using std::cin.

The program then enters a while loop that runs indefinitely (while (true)), until the user guesses the correct number and the break statement is executed. Inside the loop, the program checks whether the user’s guess is equal to the secret number using an if statement. If the guess is correct, the program prints a congratulations message and the number of tries it took to guess the number, and exits the loop using break. If the guess is incorrect, the program prints a message indicating whether the guess was too high or too low, and prompts the user to guess again.

Finally, the program returns 0 to indicate successful execution.