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: 20Machine: 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
// 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 srand ( time (NULL)); // Generate a random number number = rand () % N; printf ( "Guess a number between" " 1 and %d\n" , N); // Using a do-while loop that will // work until user guesses // the correct number do { if (numberofguess > 9) { printf ( "\nYou Loose!\n" ); break ; } // Input by user scanf ( "%d" , &guess); // When user guesses lower // than actual number if (guess > number) { printf ( "Lower number " "please!\n" ); numberofguess++; } // When user guesses higher // than actual number else if (number > guess) { printf ( "Higher number" " please!\n" ); numberofguess++; } // Printing number of times // user has taken to guess // the number else printf ( "You guessed the" " number in %d " "attempts!\n" , numberofguess); } while (guess != number); } // Driver Code int main() { int N = 100; // Function call guess(N); return 0; } |
Please Login to comment...