Click here to Skip to main content
15,887,416 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:

I am writing a simple program of a guessing game in which user have to input a number and then program tells that whether the number is too high or too low and at the end the attempts of guesses should be printed. I want to make it with only loop and if else statement. So please guide me how to do it? And how can I add for loop or while loop in it to play game again when user give wrong guess.

I tried but it doesn't work ( it gives wrong output and have many logical errors)

What I have tried:

I tried this...And i don't know how to apply loop in it.

#include<stdio.h>
int main()
{
int secret=52, tries=0;
int guess;
printf("Enter a guess number between 1 to 100\n");
scanf("%d", &guess);
if(guess==secret)
{
printf("Your guess is correct!\n***CONGRATULATIONS***\n");
tries++;
}
if(guess<secret)
{
printf("your="" guess="" is="" too="" high!\n");
="" tries++;
}
else="" if(guess="">secret)
{
printf("your guess is too low!");
tries++;
}
Printf("you guess in %d attempts, tries");
}
Posted
Updated 30-Mar-23 0:59am
v3

1 solution

You just need to wrap the code above into a loop that counts the number of tries. Somthing like:
C++
#define MAXTRIES 5 // whatever maximum you decide on
int secret=52, tries=0;
int guess;
for (tries = 0; tries < MAXTRIES; tries++)
{
    printf("Enter a guess number between 1 to 100\n");
    // the remaining code from above.
}

Note that your test for too high and too low are the wrong way round.
 
Share this answer
 
Comments
nani jan 30-Mar-23 8:26am    
@RichardMacCutchan thanks alot!!! You cleared my logics regarding for loop. Thanks♥️

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900