Home >Backend Development >C++ >Write a C program to play a guessing game

Write a C program to play a guessing game

WBOY
WBOYforward
2023-09-11 08:41:091062browse

Write a C program to play a guessing game

Question

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.

Solution

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);

Example

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);
}

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete