You’re going to make a “Guess the Number” game. The computer will think of a ran
ID: 3839819 • Letter: Y
Question
You’re going to make a “Guess the Number” game. The computer will think of a random number from 1 to 20, and ask you to guess it. The computer will tell you if each guess is too high or too low. You win if you can guess the number within six tries.
This is a good game to code because it uses random numbers, loops, and input from the user in a short program. You’ll learn how to convert values to different data types, and why you would need to do this. Since this program is a game, we’ll call the user the player. But “user” would be correct too.
Sample Run of Guess the Number
Here’s what the program looks like to the player when run. The text that the player types in is in bold.
Hello! What is your name?
Albert
Well, Albert, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too high.
Take a guess.
2
Your guess is too low.
Take a guess.
4
Good job, Albert! You guessed my number in 3 guesses!
Explanation / Answer
Here you go champ! I got the C code ready for you!
#include<stdio.h>
#include<math.h>
int main() {
int ran,guess,count;
char name[50];
printf("Hello! What is your name? ");
gets(name); //accept name
printf("Well, %s, I am thinking of a number between 1 and 20. ", name);
ran = rand() % 20 + 1; //generate random nuber between 1 -20
do {
printf("Take a guess "); //ask to enter a number
scanf("%d",&guess); //accept a number
if (guess > ran)// if guess is more than the random number generated
printf("Your guess is too high ");
else if(guess < ran) // if guess is lower than the random number generated
printf("Your guess is too low ");
count++;
}while(guess!=ran);
if (count <= 6) // checks if the user is the winner
printf("Good job, %s! You guessed the number in %d guesses! ",name, count);
else
printf("Better luck next time, %s! You guessed the number in %d guesses! ", name, count);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.