
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C Program for Guessing the Number Game
Problem
In a program a number is already initialized to some constant. Here, we have to ask the user to guess that number which is already in the program. For this, we need to provide some clues for every time the user entering the number.
Solution
The logic that is 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
"); count++; } else { flag=1; printf("Your guess is greater than the number
"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it
"); scanf("%d",&guess); } } while(flag);
Example
Following is the C program for guessing the number game.
#include<stdio.h> main() { int i,num=64,flag=1,guess,count=0; printf("guess the number randomly here are some clues later
"); scanf("%d",&guess); do { if(num==guess) { flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number
"); count++; } else { flag=1; printf("Your guess is greater than the number
"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it
"); scanf("%d",&guess); } } while(flag); printf("Congratulations! You guessed the correct number %d
",num); printf("Total number of trails you attempted for guessing is: %d
",count); }
Output
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
Advertisements