Write a C program that uses the function rand() to generate an integer randomly
ID: 3678646 • Letter: W
Question
Write a C program that uses the function rand() to generate an integer randomly in the range of 1 to 50. The random number generated by the program shall be different at each run. The program then prompts the user to guess the number by displaying the following messages: After the user's initial guess, the program should display one of the following responses: Correct! That's the number. Would you like to play again (y or n)? Too low. Guess again. Too high. Guess again. The program should loop until the user guesses the correct answer. Use the "Too low" and "Too high" messages to help the user guess the number. Once the user guesses the right number, the program should ask whether he/she would like to play again. Describe your algorithm in procedures, pseudocode, and flowchart.Explanation / Answer
Answer:
Note: printing statements are already provided
Program code:
#include<stdio.h>
#include <ctime>
#include <iomanip>
#include <cstdlib>
using namespace std;
//method declaration
int GuessGame(int guess1,int maxGuesses)
{
srand(time(0));
int rnumber= rand()%50;
char agains = 'y';
//performs random guessing game functions
do
{
if (rnumber > guess1)
{
printf("Too low, Try again. ");
scanf("%d",&guess1);
}
else if (rnumber < guess1)
{
printf("Too high, Try again. ");
scanf("%d",&guess1);
}
else if ( rnumber == guess1)
{
printf("You have found the random number!");
}
else
{
printf("Would you like to play again? (y or
n)");
scanf("%s",&agains);
}++maxGuesses;
}
while (maxGuesses < 10);
}
//main method
int main()
{
//declaring the variables
int guess1,maxGuesses=0;
//getting the USER input
printf("I have a number between 1 and 50.");
printf("Can you guess the number?");;
printf("Enter your initial Guess:");
scanf("%d",&guess1);
//call of guessing game method
GuessGame(guess1,maxGuesses);
return 0;
}
Output:
I have a number between 1 and 50
Can you guess the number?
Enter your initial Guess:
23
Too high! Try again 10
Too high! Try again 8
Too high! Try again 5
Too high! Try again 1
Too low! Try again 2
You have found the random number
Would you like to continue again? Y or n
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.