CC · Lesson 7 of 8

Mini Project: Number Guessing Game

Let's build something interactive: a number guessing game that uses everything we've learned.

C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_GUESSES 7
#define MIN_NUMBER  1
#define MAX_NUMBER  100

int clamp(int val, int min, int max) {
    if (val < min) return min;
    if (val > max) return max;
    return val;
}

void play_game() {
    srand((unsigned int)time(NULL));  // seed random number generator
    int secret = (rand() % MAX_NUMBER) + MIN_NUMBER;
    int guess, guesses_left = MAX_GUESSES;

    printf("\n=== Number Guessing Game ===\n");
    printf("Guess a number between %d and %d.\n", MIN_NUMBER, MAX_NUMBER);
    printf("You have %d guesses.\n\n", MAX_GUESSES);

    while (guesses_left > 0) {
        printf("Guesses left: %d. Your guess: ", guesses_left);

        if (scanf("%d", &guess) != 1) {
            // Clear invalid input
            while (getchar() != '\n');
            printf("Please enter a number.\n");
            continue;
        }

        guess = clamp(guess, MIN_NUMBER, MAX_NUMBER);
        guesses_left--;

        if (guess < secret) {
            printf("Too low!\n");
        } else if (guess > secret) {
            printf("Too high!\n");
        } else {
            int used = MAX_GUESSES - guesses_left;
            printf("Correct! You got it in %d guess%s!\n",
                   used, used == 1 ? "" : "es");
            return;
        }
    }

    printf("Out of guesses! The number was %d.\n", secret);
}

int main() {
    char play_again;
    do {
        play_game();
        printf("\nPlay again? (y/n): ");
        scanf(" %c", &play_again);
    } while (play_again == 'y' || play_again == 'Y');

    printf("Thanks for playing!\n");
    return 0;
}
Bash
gcc -o guess guess.c
./guess
◆ Note
Notice the scanf(" %c", ...) with a space before %c — this skips whitespace (including newlines) left in the input buffer from the previous scanf. Input handling is a common source of bugs in C programs.