Q:

Write a C program to generate and guess random number

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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!

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a C program to check given string is valid I... >>
<< Write a C program to design love calculator and ca...