That was interseting, I used recursion instead of loops here. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Recursive function to guess the secret number
void guess_number(int secret_number, int max_guesses, int num_guesses) {
// Prompt the user to enter a guess
printf("Guess #%d: ", num_guesses + 1);
int guess;
scanf("%d", &guess);
// Check if the guess is correct, higher or lower than the secret number
if (guess == secret_number) {
printf("You guessed the number!!");
} else {
if (guess < secret_number) {
printf("The number you are looking for is higher\\");
} else {
printf("The number you are looking for is lower\\");
}
// Check if the maximum number of guesses has been reached
if (num_guesses == max_guesses - 1) {
printf("You took longer than %d guesses, you lose!\\", max_guesses);
} else {
// Make a recursive call to guess_number with an incremented number of guesses
guess_number(secret_number, max_guesses, num_guesses + 1);
}
}
}
int main() {
// Generate a random number between 0 and 1000
srand(time(0));
int secret_number = rand() % 1001;
// Set the maximum number of guesses to 10
int max_guesses = 10;
// Start the game
printf("Guess the secret number between 0 and 1000 in %d guesses or less.\\", max_guesses);
// Start the recursive function with the initial values
guess_number(secret_number, max_guesses, 0);
return 0;
}