Number guessing game in Python and C

Last Updated : 11 Jun, 2026

The number guessing game is a programming project used to demonstrate concepts such as random number generation, loops, conditional statements, and user interaction. The program randomly selects a number from a user-defined range and guides the player toward the correct answer by indicating whether each guess is higher or lower than the target number.

How the Game Works

To understand how the number guessing game functions, let’s walk through two practical scenarios. These examples demonstrate how narrowing down the range intelligently, similar to a binary search can help guess the number efficiently.

Example 1: Guessing in a Range from 1 to 100

Suppose the user defines the range from 1 to 100, and the system randomly selects 42 as the target number. The guessing process might look like this:

  • 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: 41 → Too low
  • Guess 7: 42 → Correct!

Total Guesses: 7

Example 2: Guessing in a Range from 1 to 50

Now consider a smaller range, from 1 to 50, with the same target number 42. Here's how the guesses might proceed:

  • Guess 1: 25 → Too low
  • Guess 2: 37 → Too low
  • Guess 3: 43 → Too high
  • Guess 4: 40 → Too low
  • Guess 5: 41 → Too low
  • Guess 6: 42 → Correct!

Total Guesses: 6

Note: In both examples, the maximum number of chances is calculated using the binary search principle. However, the user is free to choose any guessing strategy during gameplay.

Algorithm

  1. Read the lower and upper bounds from the user.
  2. Generate a random number between the specified bounds.
  3. Repeatedly accept guesses from the user until the maximum number of attempts is reached.
  4. Indicate whether each guess is too high or too low.
  5. Stop the game when the correct number is guessed and display the result.
  6. If the user fails to guess the number, display the correct answer and a game-over message.

C Implementation

Below is the Implementation of the Algorithm in C:

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

int main()
{
    int lower, upper, target, guess;
    int count = 0, flag = 0;
    int total_chances;

    // Take lower bound input
    printf("Enter Lower Bound: ");
    scanf("%d", &lower);

    // Take upper bound input
    printf("Enter Upper Bound: ");
    scanf("%d", &upper);

    // Validate range
    if (lower >= upper) {
        printf("Error: Upper bound must be greater than lower bound.\n");
        return 0;
    }

    // Seed the random number generator
    srand(time(0));

    // Generate a random number within the range
    target = (rand() % (upper - lower + 1)) + lower;

    // Calculate maximum chances using binary search principle
    total_chances = (int)ceil(log(upper - lower + 1) / log(2));

    // Ensure at least one chance
    if (total_chances < 1) {
        total_chances = 1;
    }

    printf("\nYou have only %d chances to guess the number!\n\n",
           total_chances);

    // Guessing loop
    while (count < total_chances) {
        count++;

        printf("Guess a number: ");
        scanf("%d", &guess);

        if (guess == target) {
            printf("\nCongratulations! You guessed the number in %d attempt(s).\n",
                   count);
            flag = 1;
            break;
        }
        else if (guess < target) {
            printf("You guessed too low!\n");
        }
        else {
            printf("You guessed too high!\n");
        }
    }

    // If user fails to guess the number
    if (!flag) {
        printf("\nThe correct number was %d.\n", target);
        printf("Better luck next time!\n");
    }

    return 0;
}

Output

Outputsforguessinggame
Number guessing game

Explanation:

  • Read User Input: The program accepts the lower and upper bounds and validates that the upper bound is greater than the lower bound.
  • Generate Random Number: The rand() function is used to generate a random number within the specified range after seeding the random number generator with srand(time(0)).
  • Calculate Allowed Attempts: The maximum number of guesses is determined using the binary-search-based formula ceil(log(range_size) / log(2)).
  • Process User Guesses: A while loop repeatedly accepts guesses from the user until the correct number is guessed or all attempts are exhausted.

Python Implementation

Below is the Implementation of the Algorithm in Python:

Python
import random

print("Hi! Welcome to the Number Guessing Game.\nYou have 7 chances to guess the number. Let's start!")

low = int(input("Enter the Lower Bound: "))
high = int(input("Enter the Upper Bound: "))

print(f"\nYou have 7 chances to guess the number between {low} and {high}. Let's start!")

num = random.randint(low, high) 
# Total allowed chances
ch = 7 
# Guess counter
gc = 0                         

while gc < ch:
    gc += 1
    guess = int(input('Enter your guess: '))

    if guess == num:
        print(f'Correct! The number is {num}. You guessed it in {gc} attempts.')
        break

    elif gc >= ch and guess != num:
        print(f'Sorry! The number was {num}. Better luck next time.')

    elif guess > num:
        print('Too high! Try a lower number.')

    elif guess < num:
        print('Too low! Try a higher number.')

Output

Outputsforguessinggame

Explanation:

  • Generate a Random Number: The program uses random.randint() to generate a random number within the user-defined range.
  • Accept User Guesses: The user is given 7 chances to guess the generated number.
  • Provide Feedback: After each guess, the program indicates whether the guessed number is too high or too low.
  • Check for Success: If the user guesses the correct number, a success message is displayed along with the number of attempts used.
  • Handle Game Over: If all attempts are exhausted without a correct guess, the program reveals the correct number and displays a game-over message.

Time Complexity Analysis

  • Time Complexity: O(n) in the worst case, where n is the maximum number of allowed guesses. The program may need to compare each user guess with the generated number until all attempts are exhausted.
  • Space Complexity: O(1) as the program uses only a constant amount of extra memory regardless of the input range.
Comment