A Guessing Game In C Programming
Today we will make a simple guessing game in c language. In this we are taking 3 variables answer which contains the correct answer which we have taken it as 42 some random number, a guess variable which is of integer datatype which we will input from user and the index variable i. The user will get 3 chances to guess the correct answer which is 42, if the user fails to guess the number 42 then we will display you lost and try again. If he guess the correct answer then we will display correct answer and if the number is greater or lesser then we will display the same as shown below in the program.
Guessing game in c |
Learn if-else statements.
Algorithm:-
- Start
- Initialize answer to 42
- while i<3 run the loop
- Read the guess number
- if guess is equal to answer than print correct answer and break from loop, else if less than answer print less than answer, else print greater than answer
- if i is greater than or equal to 3 print try again
- Stop.
Program:-
In this simple guessing game c program. First we set a number that the user will guess in the answer variable 42 in this program. We are giving three tries to user within three tries the user has to find the correct guess. Inside the while loop we are taking the user guess and storing the number in variable guess. if the guess is equal to answer then we print correct answer and break out of the loop, else if the guess is less than the answer print guess is less than answer and if the guess is greater than answer than print guess is greater than answer. If you didn't find guess the correct number then prints you lost. Refer the program given below
#include <stdio.h>
int main()
{
int guess, answer, i=0;
printf("*****A GUESSING GAME*****");
answer = 42; //let the answer be 42
printf("\nYou have 3 chances to guess correct number");
while(i<3){
printf("\nEnter guess number: ");
scanf("%d", &guess);
if(guess==answer){
printf("Correct Answer!!!");
break;
} else if (guess<answer){
printf("Guess is less than the answer");
} else {
printf("Guess is greater than the answer");
}
i++;
}
if(i>=3){
printf("\n\nYou lost the game. Try Again!");
}
return 0;
}
Output:-
*****A GUESSING GAME*****
You have 3 chances to guess correct number
Enter guess number: 32
Guess is less than the answer
Enter guess number: 4
Guess is less than the answer
Enter guess number: 49
Guess is greater than the answer
You lost the game. Try Again!
*****A GUESSING GAME*****
You have 3 chances to guess correct number
Enter guess number: 42
Correct Answer!!!
0 Comments