# Guess A Number Game , How To Add Or Display Number Of Guesses Left Using While Loop

## 11 July 2020 - 1 answer

Number guessing game which a user guess a number from 0-20 and i want it to display how many tries are left for the user for example the maximum tries is 5 and if the user got it wrong on the first try it will display something like "tries left : 4", how do i implement that in my code?

``````#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
time_t t;
srand((unsigned)time(&t));
int randomNumber = rand() % 21;
int num;
int guess = 0;

printf("\nThis is a guessing game.");
printf("\nGuess 5 times only\n");

scanf("%d",&num);

while (num != randomNumber && guess < 5){ //checks if num is equal or not to randomnumber and count is less than 5 or limit 5

if(num > randomNumber){ // checks if num is greater than randomNumber
printf("Too high! try again:");
scanf("%d",&num);
guess++;
}

if(num < randomNumber){ //checks if num is less than randomNumber
printf("Too low! try again:");
scanf("%d",&num);
guess++;
}

if(num == randomNumber){ //checks if num is equal to randomNumber
printf("You got it right!\n");
return 0;
}

if(guess == 5) //checks if tries is 5 then exits program.
{
return 0;
}

}

return 0;
}

``````
``````// For total no of guesses = 5, if that is n then n - 1 - guess