Number Guessing Game | While Loop
Number Guessing Game:
The following program randomly generates an integer greater than or equal to 0 and less than 100. The program then prompts the user to guess the number. If the user guesses the number correctly, the program outputs an appropriate message. Otherwise, the program checks whether the guessed number is less than the random number. If the guessed number is less than the random number generated by the program, the program outputs the message “Your guess is lower than the number. Guess again!”; otherwise, the program outputs the message “Your guess is higher than the number. Guess again!”. The program then prompts the user to enter another number. The user is prompted to guess the random number until the user enters the correct number.
To generate a random number, you can use the function rand from the header file cstdlib. For example, the expression rand() returns an int value between 0 and 32767. Therefore, the statement:
cout << rand() << ", " << rand() << endl;
will output two numbers that appear to be random. However, each time the programis run, this statement will output the same random numbers. This is because thefunction rand uses an algorithm that produces the same sequence of random numberseach time the program is executed on the same system. To generate different random numbers each time the program is executed, you also use the function srand from the header file cstdlib. The function srand takes as input an unsigned int, which acts as the seed for the algorithm. By specifying different seed values, each time the program is executed, the function rand will generate a different sequence of random numbers. To specify a different seed, you can use the function time from the header file ctime, which returns the number of seconds elapsed since January 1, 1970. For example, consider the following statements:
srand(time(0));
num = rand() % 100;
The first statement sets the seed, and the second statement generates a random number greater than or equal to 0 and less than 100. Note how the function time is used. It is used with an argument, that is, parameter, which is 0.
The program uses the bool variable isGuessed to control the loop. The bool variable isGuessed is initialized to false. It is set to true when the user guesses the correct number.
Sample Run: In this sample run, the user input is shaded.
Enter an integer greater than or equal to 0 and less than 100: 45
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 20
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 35
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 28
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 32
You guessed the correct number.
Comments
Post a Comment