Random Number Guessing Game Write a program that generates a random number and a
ID: 3627135 • Letter: R
Question
Random Number Guessing Game
Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again”. The program should use a loop that repeats until the user correctly guesses the random number. When the user guesses correctly, the program should display “That’s right” along with the number of guesses that the user made (count the guesses inside the loop).
After the number has been correctly guessed, ask the user if they would like to play again and then loop back around to generate and take guesses for another number. Keep playing the game until the user asks not to play again.
Use separate functions to generate the random number, read a guess from the user and display the correct message. The logic to loop until the number is guessed correctly, to count the guesses and to loop back to play again can be in main.
Section 3.11 and Example Program 3-26 in your book will show you how to use the random number generator. The Unit 3 notes include additional examples of the random number generator. You should seed the random number generator in main with srand and generate the next random number with rand in a separate function as described above.
Explanation / Answer
Below is the code in C. I am not sure what language you were looking for. This works and gives the looping answer. #include main() { int target; int guess; int again; printf(" Do you want to guess a number 1 =Yes, 0=No "); scanf("%d",&again); while (again) { target = rand() % 100; guess = target + 1; while(target!=guess) { printf(" What is your guess ? "); scanf("%d",&guess); if (target>guess) printf("Too low"); else printf("Too high"); } printf(" Well done you got it! "); printf(" Do you want to guess a number 1=Yes, 0=No"); scanf("%d", &again); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.