C Project: Number Guessing Game
A guessing game puts loops, input, and decisions together. The program picks a secret number, and the player guesses until it matches.
Pick a secret number
srand(42) sets the starting point, and rand() % 100 + 1 picks a number from 1 to 100. With this starting point, the secret is 67.
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(42);
int secret = rand() % 100 + 1;
printf("Secret number is %d\n", secret);
return 0;
}One hint
One guess is read and tested against a secret of 50. A guess of 30 is below it, so the output is Too low.
#include <stdio.h>
int main() {
int secret = 50;
int guess = 0;
printf("Enter a guess.\n");
scanf("%d", &guess);
if (guess < secret) {
printf("Too low\n");
} else if (guess > secret) {
printf("Too high\n");
} else {
printf("Correct!\n");
}
return 0;
}Loop until correct
The loop keeps asking until a guess matches. The guesses 30, 70, and 50 take three tries.
#include <stdio.h>
int main() {
int secret = 50;
int guess = 0;
int tries = 0;
while (guess != secret) {
printf("Enter a guess.\n");
scanf("%d", &guess);
tries++;
if (guess < secret) {
printf("Too low\n");
} else if (guess > secret) {
printf("Too high\n");
}
}
printf("Correct! You found it in %d tries.\n", tries);
return 0;
}Example
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(42);
int secret = rand() % 100 + 1;
int guess = 0;
int tries = 0;
printf("Guess a number between 1 and 100.\n");
while (guess != secret) {
printf("Enter a guess.\n");
scanf("%d", &guess);
tries++;
if (guess < secret) {
printf("Too low\n");
} else if (guess > secret) {
printf("Too high\n");
}
}
printf("Correct! You found it in %d tries.\n", tries);
return 0;
}Key points
- srand sets the starting point for random numbers.
- srand(42) gives the same secret every run, so the game can be checked.
- rand gives a number that looks random.
- rand() % 100 + 1 gives a number from 1 to 100.
- A while loop keeps asking for guesses until the guess matches.
- scanf reads each guess from the player.
- A guess below the secret prints Too low, and a guess above it prints Too high.
- A counter counts the tries.
srand(42) picks 67 as the secret number. The first guess, 50, is too low. The second guess, 80, is too high. The third guess, 67, matches, so the game ends after 3 tries.
Note
srand and rand come from stdlib.h, so the program includes that file too.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does the program call srand(42)?