Learn C · lesson 20 of 60 · about 9 minutes
Project: Number Guessing
Lock the admin menu behind a secret number: loop until the guess is right or the guesses run out, with a hint after each wrong one.
What you'll learn
- Loop until a condition is met
- Count attempts
- Give higher/lower hints
The admin lock
The report's last part is an admin menu, locked with a secret number from 1 to 100. The user gets 5 guesses, and after each wrong one the report says Too low or Too high. The loop has two ways out: a right guess, or no guesses left.
How the game works
1. The program has a secret number
2. Each round, read a guess and count it
3. Say "Too low" or "Too high" until the guess is right
4. Then report how many guesses it took
Real games pick a random secret with rand(). Here it's fixed at 37 so you can predict the output.
The game
#include <stdio.h>
int main(void) {
const int secret = 37;
int guess = 0;
int tries = 0;
while (guess != secret) {
printf("Guess: ");
scanf("%d", &guess);
tries++;
if (guess < secret) {
printf("Too low\n");
} else if (guess > secret) {
printf("Too high\n");
}
}
printf("Got it in %d tries!\n", tries);
return 0;
}Output
Guess: Too high
Guess: Too low
Guess: Got it in 3 tries!The admin lock, with a limit
#include <stdio.h>
int main(void) {
const int SECRET = 37;
printf("Admin menu locked. Guess the number (1-100).\n");
int guess = 0;
int tries = 0;
while (guess != SECRET && tries < 5) {
scanf("%d", &guess);
tries++;
if (guess < SECRET) {
printf("Too low\n");
} else if (guess > SECRET) {
printf("Too high\n");
}
}
if (guess == SECRET) {
printf("Unlocked! Guesses: %d\n", tries);
} else {
printf("Locked out.\n");
}
return 0;
}Output
Admin menu locked. Guess the number (1-100).
Too high
Too low
Unlocked! Guesses: 3Tip
After the loop, check why it ended: guess == SECRET means the user got in, and anything else means the guesses ran out.
Tip
Halving the range each time (50, then 25, then 37...) finds any number from 1 to 100 in at most 7 guesses. That idea is called binary search.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.