Write a C program for guessing the number game.

CServer Side ProgrammingProgramming

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\n");
      count++;
   } else {
      flag=1;
      printf("Your guess is greater than the number\n");
      count++;
   } if(flag==1) {
      printf("sorry wrong enter! once again try it\n");
      scanf("%d",&guess);
   }
} while(flag);

Example

Following is the C program for guessing the number game.

 Live Demo

#include<stdio.h>
main() {
   int i,num=64,flag=1,guess,count=0;
   printf("guess the number randomly here are some clues later\n");
   scanf("%d",&guess);
   do {
      if(num==guess) {
         flag=0;
      } else if(guess<num) {
         flag=1;
         printf("Your guess is lower than the number\n");
         count++;
      } else {
         flag=1;
         printf("Your guess is greater than the number\n");
         count++;
      }
      if(flag==1) {
         printf("sorry wrong enter! once again try it\n");
         scanf("%d",&guess);
      }
   } while(flag);
   printf("Congratulations! You guessed the correct number %d\n",num);
   printf("Total number of trails you attempted for guessing is: %d\n",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
raja
Published on 25-Mar-2021 07:27:39
Advertisements