Skip to content

Practice Problem 7

Seanti edited this page Mar 26, 2025 · 1 revision

Problem:

Create a number guessing game where the program generates a random number (1-10). The user keeps guessing until they get the correct number.

  • Use a while loop to keep asking for guesses until the correct number is guessed.

  • Use a for loop to limit the number of guesses to a maximum of 5.

  • Use a do-while loop to ask the user if they want to play again.


Sample Output:

User wins within 5 attempts:

Guess a number (1-10): 3  
Too low! Try again.  
Guess a number (1-10): 7  
Too high! Try again.  
Guess a number (1-10): 5  
Correct!  

Do you want to play again? (yes/no): yes  
Guess a number (1-10): 8  
Too high! Try again.  
Guess a number (1-10): 2  
Correct!  

Do you want to play again? (yes/no): no  
Thanks for playing!

User runs out of guesses (5 attempts):

Guess a number (1-10): 1  
Too low! Try again.  
Guess a number (1-10): 2  
Too low! Try again.  
Guess a number (1-10): 9  
Too high! Try again.  
Guess a number (1-10): 6  
Too high! Try again.  
Guess a number (1-10): 4  
Out of attempts! The correct number was 5.  

Do you want to play again? (yes/no): no  
Thanks for playing!

How the Loops Work in This Problem:

while loop → Keeps asking for a guess until the correct number is found or attempts run out.
for loop → Limits the user to 5 attempts.
do-while loop → Ensures the user is asked if they want to play again at least once.

Clone this wiki locally