Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Number guessing game in C

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an integer N. A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end after 10 attempts and if the player failed to guess the number, and then he loses the game.


N = 100
Number chosen: 20 

Machine: Guess a number between 1 and N
Player: 30
Machine: Lower number please!
Player: 15
Machine: Higher number please!
Player: 20
Machine: You guessed the number in 3 attempts
Now, terminate the game.

Approach: The following steps can be followed to design the game:

  • Generate a random number between 0 and N.
  • Then iterate from 1 to 10 and check if the input number is equal to the assumed number or not.
  • If yes, then the player wins the game.
  • Otherwise, terminate the game after 10 attempts.

Below is the implementation of the above approach:


// C program for the above approach
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function that generate a number in
// the range [1, N] and checks if the
// generated number is the same as the
// guessed number or not
void guess(int N)
    int number, guess, numberofguess = 0;
    //Seed random number generator
    // Generate a random number
    number = rand() % N;
    printf("Guess a number between"
           " 1 and %d\n",
    // Using a do-while loop that will
    // work until user guesses
    // the correct number
    do {
        if (numberofguess > 9) {
            printf("\nYou Loose!\n");
        // Input by user
        scanf("%d", &guess);
        // When user guesses lower
        // than actual number
        if (guess > number)
            printf("Lower number "
        // When user guesses higher
        // than actual number
        else if (number > guess)
            printf("Higher number"
                   " please!\n");
        // Printing number of times
        // user has taken to guess
        // the number
            printf("You guessed the"
                   " number in %d "
    } while (guess != number);
// Driver Code
int main()
    int N = 100;
    // Function call
    return 0;


My Personal Notes arrow_drop_up
Last Updated : 01 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials