Skip to content
StudyFame

Number Guessing Game in C

The computer thinks of a number between 1 and 100, and you try to guess it. After each guess it says "Too high" or "Too low". It's a tiny game, but it uses some important ideas: random numbers, loops that stop on a condition, counting attempts and keeping score.

In this project you will learn how rand() and srand() work, build the basic game with a limited number of attempts, and then add difficulty levels, a score and a play again option. You'll also learn a trick to make random programs testable.

What You Will Learn

  • How to generate random numbers with rand().
  • Why srand(time(NULL)) is needed.
  • How to get a random number in a range.
  • How to loop until the user guesses or runs out of attempts.
  • How to add levels, scoring and a play-again loop.
  • How to test a program that uses random numbers.

Number Guessing Game in C Explained

Exam definition: rand() (from <stdlib.h>) returns a pseudo-random integer between 0 and RAND_MAX. The numbers come from a formula, so the same seed always produces the same sequence. srand(seed) sets the seed; calling srand(time(NULL)) once at the start uses the current time, so each run gives different numbers. A random integer from low to high is rand() % (high - low + 1) + low.

Memory trick: rand() is a song playlist on shuffle that was shuffled once in the factory: the order looks random, but it's the same every time you switch it on. srand(time(NULL)) reshuffles it using the clock, so every game starts differently. Shuffle once, at the start, not before every song.

Syntax: Random Numbers in a Range

#include <stdlib.h>   /* rand, srand */
#include <time.h>     /* time */

srand((unsigned) time(NULL));          /* once, at the start of main */

int dice   = rand() % 6 + 1;           /* 1 to 6   */
int secret = rand() % 100 + 1;         /* 1 to 100 */
int n      = rand() % (high - low + 1) + low;   /* low to high */
ExpressionRange
rand() % 100 to 9
rand() % 10 + 11 to 10
rand() % 51 + 5050 to 100

Example 1: Guess the Number (1 to 100, 7 Attempts)

For testing, you can give the secret number on the command line: ./guess 42. Without it, the number is random.

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

#define MAX_TRIES 7

int main(int argc, char *argv[])
{
    int secret, guess, tries = 0;

    if (argc > 1)
        secret = atoi(argv[1]);              /* testing: ./guess 42 */
    else
    {
        srand((unsigned) time(NULL));
        secret = rand() % 100 + 1;           /* 1 to 100 */
    }

    printf("I'm thinking of a number between 1 and 100.\n");
    printf("You have %d tries.\n", MAX_TRIES);

    while (tries < MAX_TRIES)
    {
        printf("Guess #%d: ", tries + 1);
        if (scanf("%d", &guess) != 1)
        {
            printf("That's not a number.\n");
            return 1;
        }
        tries++;

        if (guess < 1 || guess > 100)
            printf("Please guess between 1 and 100.\n");
        else if (guess < secret)
            printf("Too low!\n");
        else if (guess > secret)
            printf("Too high!\n");
        else
        {
            printf("Correct! You guessed it in %d tries.\n", tries);
            return 0;
        }
    }
    printf("Out of tries! The number was %d.\n", secret);
    return 0;
}

Output

I'm thinking of a number between 1 and 100.
You have 7 tries.
Guess #1: 50
Too high!
Guess #2: 25
Too low!
Guess #3: 37
Too low!
Guess #4: 43
Too high!
Guess #5: 40
Too low!
Guess #6: 42
Correct! You guessed it in 6 tries.

Code Explanation

  1. srand((unsigned) time(NULL)) seeds the generator with the current time, so the secret changes every run. It is called once.
  2. rand() % 100 gives 0 to 99; adding 1 gives 1 to 100.
  3. The argc > 1 branch is a testing trick: passing the secret on the command line makes the game repeatable, so you (and your teacher) can check every message.
  4. The while loop runs at most MAX_TRIES times. A correct guess ends the program early with return 0.
  5. Guesses outside 1–100 still use up a try, but get a helpful message.

How the Best Strategy Works

The player above used binary search: always guess the middle of the remaining range.

range 1..100  guess 50 -> too high  -> range 1..49
range 1..49   guess 25 -> too low   -> range 26..49
range 26..49  guess 37 -> too low   -> range 38..49
range 38..49  guess 43 -> too high  -> range 38..42
range 38..42  guess 40 -> too low   -> range 41..42
range 41..42  guess 42 -> correct!

Each guess halves the range, so any number from 1 to 100 can be found in at most 7 guesses (27 = 128 ≥ 100). That's why the game gives 7 tries.

Example 2: Levels, Score and Play Again

Run as ./game for random numbers, or ./game 7 63 to fix the secret of round 1 and round 2 for testing.

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

int play_round(int max, int tries_allowed, int secret)
{
    int guess, tries;

    printf("Guess a number from 1 to %d (%d tries)\n", max, tries_allowed);
    for (tries = 1; tries <= tries_allowed; tries++)
    {
        printf("Try %d: ", tries);
        if (scanf("%d", &guess) != 1)
            return 0;
        if (guess == secret)
        {
            int points = (tries_allowed - tries + 1) * 10;
            printf("Correct! +%d points\n", points);
            return points;
        }
        printf(guess < secret ? "Higher\n" : "Lower\n");
    }
    printf("No more tries. It was %d.\n", secret);
    return 0;
}

int main(int argc, char *argv[])
{
    int level, max, tries, secret, score = 0, round = 0;
    char again;

    srand((unsigned) time(NULL));
    do
    {
        round++;
        printf("\nRound %d - choose level (1 = easy, 2 = hard): ", round);
        if (scanf("%d", &level) != 1)
            break;
        max = (level == 1) ? 10 : 100;
        tries = (level == 1) ? 4 : 7;

        if (round < argc)
            secret = atoi(argv[round]);          /* fixed secret for testing */
        else
            secret = rand() % max + 1;

        score += play_round(max, tries, secret);
        printf("Total score: %d\n", score);
        printf("Play again? (y/n): ");
        if (scanf(" %c", &again) != 1)
            break;
    } while (again == 'y' || again == 'Y');

    printf("Thanks for playing! Final score: %d\n", score);
    return 0;
}

Output

Round 1 - choose level (1 = easy, 2 = hard): 1
Guess a number from 1 to 10 (4 tries)
Try 1: 5
Higher
Try 2: 8
Lower
Try 3: 7
Correct! +20 points
Total score: 20
Play again? (y/n): y

Round 2 - choose level (1 = easy, 2 = hard): 2
Guess a number from 1 to 100 (7 tries)
Try 1: 50
Higher
Try 2: 75
Lower
Try 3: 63
Correct! +50 points
Total score: 70
Play again? (y/n): n
Thanks for playing! Final score: 70
  • play_round() runs one game and returns the points: fewer tries used = more points. Round 1: (4 − 3 + 1) × 10 = 20. Round 2: (7 − 3 + 1) × 10 = 50.
  • The do-while loop plays at least one round and repeats while the answer is y.
  • scanf(" %c", &again) has a space before %c. It skips the newline left from the previous input; without it, again would read '\n'.
  • The level changes both the range and the number of tries, using the conditional operator.

Important Points to Remember

  • rand() gives pseudo-random numbers from 0 to RAND_MAX.
  • Call srand(time(NULL)) once at the start; otherwise every run gives the same numbers.
  • Range low..high: rand() % (high − low + 1) + low.
  • Limit attempts with a counter; end early when the guess is correct.
  • Use " %c" (with a space) to read a y/n answer after numbers.
  • For testing, allow a fixed secret (command-line argument or fixed seed).

Common Mistakes Beginners Make

MistakeWhat happensFix
No srandSame "random" number every runsrand(time(NULL)) once
srand inside the loopSame number repeated within one secondSeed only once, before the loop
rand() % 100 for 1–100Range is 0–99Add 1
scanf("%c", &again)Reads the leftover newline; loop ends at onceUse " %c"
Forgetting #include <time.h>Warning or error for timeInclude time.h

Number Guessing Game Practice Questions

  1. What does rand() return? Which header declares it?
  2. Why do we call srand(time(NULL))?
  3. Write an expression for a random number from 20 to 30.
  4. Why are 7 tries enough to guess any number from 1 to 100?
  5. Why is there a space in scanf(" %c", &again)?
Show answers
  1. A pseudo-random integer from 0 to RAND_MAX; <stdlib.h>.
  2. To seed the generator with the current time so each run produces a different sequence.
  3. rand() % 11 + 20.
  4. With binary search each guess halves the range; 27 = 128 ≥ 100.
  5. The space skips whitespace, including the newline left by the previous scanf.

Coding Exercise

Write a dice game: roll two dice 5 times (use srand(1) so the run is repeatable on your machine), print each roll and count how many times you got a double (both dice the same). The program below shows the logic; your numbers will depend on your compiler's rand().

Show solution
#include <stdio.h>
#include <stdlib.h>

int roll(void)
{
    return rand() % 6 + 1;
}

int main(void)
{
    int i, a, b, doubles = 0, total = 0;

    srand(1);                       /* fixed seed: same rolls every run */
    for (i = 1; i <= 5; i++)
    {
        a = roll();
        b = roll();
        total += a + b;
        if (a == b)
            doubles++;
    }
    printf("Rolled 5 times, total of all dice = %d\n", total);
    printf("Doubles: %d\n", doubles);
    return 0;
}
(Sample output: the totals depend on your compiler's rand())
Rolled 5 times, total of all dice = 34
Doubles: 1

Quick Quiz: Number Guessing Game (MCQ)

  1. Which function sets the seed for rand()?

    A) seed()   B) srand()   C) random()   D) time()

  2. rand() % 6 + 1 gives numbers from:

    A) 0 to 6   B) 1 to 6   C) 0 to 5   D) 1 to 7

  3. Without srand, each run of the program:

    A) Crashes   B) Gives the same sequence   C) Gives different numbers   D) Gives only 0

  4. time(NULL) is declared in:

    A) stdlib.h   B) time.h   C) stdio.h   D) math.h

  5. Maximum guesses needed for 1 to 1000 with binary search:

    A) 7   B) 10   C) 100   D) 500

Show answers
  1. B: srand().
  2. B: 1 to 6.
  3. B: the same sequence.
  4. B: time.h.
  5. B: 10 (210 = 1024).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

rand()Pseudo-random, 0 to RAND_MAX, stdlib.h
srand(seed)Sets the seed; call once
Seed with timesrand(time(NULL)), time.h
1 to Nrand() % N + 1
low to highrand() % (high − low + 1) + low
Best strategyBinary search: 7 tries for 1–100
y/n inputscanf(" %c", ...)

Frequently asked questions

How do you generate a random number between 1 and 100 in C?
Call srand(time(NULL)) once, then use rand() % 100 + 1.
Why does rand() give the same numbers every time?
Because the generator starts from the same seed; seed it with srand(time(NULL)).
Are rand() numbers truly random?
No, they are pseudo-random: produced by a formula from the seed. Fine for games, not for security.

Remember

  • rand = pre-shuffled playlist; srand(time) = reshuffle once.
  • Range formula: % size + start.

Next Topic

Next lesson: Tic Tac Toe in C. You will use a 2D array to build a two-player Tic Tac Toe game with win detection.