In a program, a number has been initialized to a constant. Here we need to ask the user to guess that number that is already in the program. To do this, we need to provide some clues every time the user enters a number.
The logic used to guess the number is as follows −
do{ if(num==guess){ flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag);
The following is the C program for the guessing number game.
Real time demonstration
#include<stdio.h> main() { int i,num=64,flag=1,guess,count=0; printf("guess the number randomly here are some clues later</p><p>"); scanf("%d",&guess); do { if(num==guess) { flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag); printf("Congratulations! You guessed the correct number %d</p><p>",num); printf("Total number of trails you attempted for guessing is: %d</p><p>",count); }
When the above program is executed, it produces the following output −
guess the number randomly here are some clues later 45 Your guess is lower than the number sorry wrong enter! once again try it 60 Your guess is lower than the number sorry wrong enter! once again try it 70 Your guess is greater than the number sorry wrong enter! once again try it 65 Your guess is greater than the number sorry wrong enter! once again try it 62 Your guess is lower than the number sorry wrong enter! once again try it 64 Congratulations! You guessed the correct number 64 Total number of trails you attempted for guessing is: 5
The above is the detailed content of Write a C program to play a guessing game. For more information, please follow other related articles on the PHP Chinese website!