Question: 2 . ( Using simple while loop with break statement ) Write a C program that generates a random number between 1 and 5 and

2.(Using simple "while" loop with break statement)
Write a C program that generates a random number between 1 and 5 and asks the user to guess it. Use a while loop to give the user multiple chances until they guess the correct number.
```
#include
#include
#include
int main(){
srand(time(NULL)); // Seed the random number generator with the
current time
int targetNumber = rand()%5+1; // Generate a random number
between 1 and 5
int userGuess; // Variable to store the user's guess
int num_attempts =0; // Variable to count the number of attempts
printf("Guess the number between 1 and 5:
");
```
Pseudocode of your "while" loop:
1. Display "Input your guess: "
2. Read the user's guess into userGuess
3. Increment attempts by 1
4. If userGuess is equal to targetNumber, then
Display "Congratulations! You guessed the correct number in num_attempts attempts."
5. Exit the loop using "break" statement
6. Else, Display "Incorrect guess. Try again!"
Expected output:
Guess the number between 1 and 5:
Input your guess: 4
Incorrect guess. Try again!
Input your guess: 5
Incorrect guess. Try again!
Input your guess: 2
Congratulations! You guessed the correct number in 3 attempts
2 . ( Using simple "while" loop with break

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!