Question
3. Guessing Game (guess.c) Write a program similar to the one in Lab 4 over loops that prompts a user for a number and then
3. Guessing Game (guess.c) Write a program similar to the one in Lab 4 over loops that prompts a user for a number and then tells them if they are too high or too low. Instead of using a while loop as in the lab you will use a for loop and allow for a fixed number of entries. If an invalid number(a number not in the range 1-10) is entered you will ignore it and decrease the loop counter as if that entry never happened. Set the random number to be between 1 and 10 and the loop to go 10 times.
Implement this function: int check(int n, int number)
OUTPUT should be:
Enter a number: 5
Too low!
Enter a number: 11
Invallid input, number should be between 1 and 10
Enter a number: 8
Too high!
Enter a number: 6
Too low!
Enter a number: 7
Correct! Number of guesses: 4
THIS IS WHAT I HAVE SO FAR...but its wrong. Where did I go wrong?
#include
int check(int n, int number);
int main(void) {
int n = 10; int tries;
//seed the random number generator srand(time(NULL)); int number = (rand() % n) + 1; // secret number
int guess = -10; int num_guesses = 0;
printf("Guess-A-Number Game! "); printf("Enter a number between 1 and %d ", n); scanf("%d", &guess); num_guesses = num_guesses + 1; // alternative: num_guesses++ // Call function with user input tries = check(guess, number); if (tries > 0 && tries < 11) { printf("Congratulations, you found it! Number of guesses: %d ", num_guesses); } else { printf("You did not find it! Number of guesses: %d ", num_guesses); } return 0; }
int check(int n, int number) { int num_guesses = 0; int guess = -10; for (num_guesses = 1; num_guesses <= 10 && guess != number; num_guesses++) { if (guess > 0 && guess < 11) { if(guess > number) { printf("%d is too high ", guess); } else { printf("%d is too low ", guess); } printf("Enter another guess: "); scanf("%d", &guess); } else { num_guesses--; scanf("%d", &guess); } } return num_guesses; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started