119k views
5 votes
C programming

Write a program which will have you guess the secret number (stored in a variable in the code). The person should guess the secret number, which is
from 0 to 1000, in 10 guesses or less. The program will tell you whether the answer is higher, lower, or correct compared to the guess.
We will be using only condition statements (no loops, functions or anything not covered to this point!).
Example: Lets say the number is 59 (stored in a variable and the user should not know what it is.. best if generated randomly our example program
shows an example of randomly generated numbers).
Please enter a number: 300
The number you are looking for is lower
Please enter a number: 100
The number you are looking for is lower
Please enter a number: 50
The number you are looking for is higher
Please enter a number: 59
You guessed the number!!
OR if they took longer than 10 guesses
You took longer than 10 guesses, you lose!

MUST NOT BE A LOOP

User Derry
by
7.0k points

1 Answer

4 votes

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;

}

User Syclone
by
6.9k points