Number guessing game in C
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.
Examples:
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
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guess( int N)
{
int number, guess, numberofguess = 0;
srand ( time (NULL));
number = rand () % N;
printf ( "Guess a number between"
" 1 and %d\n" ,
N);
do {
if (numberofguess > 9) {
printf ( "\nYou Loose!\n" );
break ;
}
scanf ( "%d" , &guess);
if (guess > number)
{
printf ( "Lower number "
"please!\n" );
numberofguess++;
}
else if (number > guess)
{
printf ( "Higher number"
" please!\n" );
numberofguess++;
}
else
printf ( "You guessed the"
" number in %d "
"attempts!\n" ,
numberofguess);
} while (guess != number);
}
int main()
{
int N = 100;
guess(N);
return 0;
}
|
Output:
Last Updated :
01 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...