This program is a guessing game that counts how many tries it takes for a player
ID: 3571669 • Letter: T
Question
This program is a guessing game that counts how many tries it takes for a player to guess a random number in the range from 1 to 20 (inclusive) that the computer has generated. The program should prompt the user for a guess and then indicate if the guess was too high, too low, or correct. When the player guesses correctly, the program should print out how many guesses the player made. Your C code must be both well-formatted and well-commented.
Be sure to include extended comments about the loop used in your code.
Explanation / Answer
/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* main function */
int main(void) {
/* for generating the random number */
srand(time(NULL));
/* generating and storing random number in the integer variable random_number */
int random_number = rand() % 20 + 1;
/* flag variable to check wether guess is correct or not */
int correct_guess = 0;
/* variable to store guessed number by the user */
int user_guess;
/* variable to keep track of number of times user guessed to get the correct guess */
int no_of_tries = 0;
/* prompting user to enter the number guessed by him/her */
printf("Guess a random number in the range from 1 to 20 (inclusive) : ");
/* do loop while guess is incorrect */
do {
/* storing user entered guess in the variable user_guess */
scanf("%d", &user_guess);
/* user_guess is correct than print correct and number of tries */
if (user_guess == random_number) {
no_of_tries++;
printf("Guess is correct in %d tries! ", no_of_tries);
correct_guess = 1;
}
/* if user guess is less than the actual number then print low and prompt the user to guess again */
if (user_guess < random_number) {
no_of_tries++;
printf("Guess was too low,Guess again: ");
}
/* if user guess is greater than the actual number then print high and prompt the user to guess again */
if (user_guess >random_number) {
no_of_tries++;
printf("Guess was too high,Guess again: ");
}
} while (correct_guess == 0);
return 0;
}
/***********OUTPUT**********
Guess a random number in the range from 1 to 20 (inclusive) : 6
Guess was too low,Guess again: 8
Guess is correct in 2 tries!
***********OUTPUT**********/
/* Note:This code has been written in c and tested on gcc compiler,Please do ask in case of any doubt
would glad to help you,Thanks!! */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.