Building A Guessing Game
Lesson 23Author : Afrixi
Last Updated : January, 2023
here’s an example of a simple guessing game using a while loop in C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secret_number, guess;
srand(time(NULL)); // seed the random number generator
secret_number = rand() % 100 + 1; // generate a random number between 1 and 100
printf("Guess the secret number (between 1 and 100): ");
scanf("%d", &guess);
while (guess != secret_number) {
if (guess < secret_number) {
printf("Too low! Try again: ");
} else {
printf("Too high! Try again: ");
}
scanf("%d", &guess);
}
printf("Congratulations, you guessed the secret number %d!\n", secret_number);
return 0;
}
In this game, the computer generates a secret number between 1 and 100 using the srand
and rand
functions from the stdlib.h
library. The player is prompted to enter a guess using scanf
, and the program enters a while
loop that continues until the player guesses the correct number.
Inside the loop, the program uses an if
statement to check whether the player’s guess is too high or too low, and gives a corresponding message. The player is then prompted to enter another guess using scanf
. Once the player guesses the correct number, the loop ends and a congratulations message is printed. Finally, the program returns 0 to indicate successful completion.
Note that the time
function from the time.h
library is used to seed the random number generator with the current time, ensuring that the generated number is different each time the program is run.