By | 03.12.2016

# C program to generate and guess random number

Write a C program to generate and guess random number.This program will read a random number and ask to user to guess it. This is just like a small game program in which user has to guess correct number which is generated randomly.

Here program will give 7 attempts to guess the number, on each attempt program will inform that entered number is less than or greater than the random generated number so that user can easily guess that particular number.

Below is the source code of the C program to guess random number which is successfully compiled and run on the windows system.The Output of the program is shown below.

## SOURCE : :

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

int main(void) {
srand(time(NULL));

int r = rand() % 10 + 1;
bool correct = false;
int guess;
int counter = 0;

while(!correct)
{
printf("Guess my number! ");
scanf("%d", &guess);
getchar();

if (guess < r) {
printf("Your guess is too low. Guess again.\n");
}
else if (guess > r) {
printf("Your guess is too high. Guess again.\n");
}
else /* if (guess == r) */ {
printf("You guessed correctly in %d tries! Congratulations!\n", counter);
correct = true;
}

counter++;
if(counter==7){
printf("\n\n### Maximum limit of attempt finished, BAD LUCK !!!\n");
break;
}
}

return 0;
}```

Also Read : : Write a C program to implement a TIC TAC TOE game

## OUTPUT : :

```FIRST RUN :

Guess my number! 2
Your guess is too low. Guess again.
Guess my number! 5
Your guess is too low. Guess again.
Guess my number! 8
Your guess is too low. Guess again.
Guess my number! 0
Your guess is too low. Guess again.
Guess my number! 22
Your guess is too high. Guess again.
Guess my number! 15
Your guess is too high. Guess again.
Guess my number! 13
Your guess is too high. Guess again.

### Maximum limit of attempt finished, BAD LUCK !!!

SECOND RUN :

Guess my number! 4
Your guess is too low. Guess again.
Guess my number! 9
Your guess is too high. Guess again.
Guess my number! 7
You guessed correctly in 3 tries! Congratulations!```
0 0 votes
Article Rating
Category: Advance Programs C Programming Tags:

## About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments