I like to play games
Understood, I'll provide explanations for each step in C.
#include <stdio.h>
int main() {
int secretNumber = 7;
int guess;
do {
printf("Guess the secret number: ");
scanf("%d", &guess);
if (guess < secretNumber) {
printf("Too low! Try again.\n");
} else if (guess > secretNumber) {
printf("Too high! Try again.\n");
} else {
printf("Congratulations! You guessed the secret number.\n");
}
} while (guess != secretNumber);
return 0;
}
Explanation:
#include <stdio.h>
: Includes the standard input-output library for basic input and output operations.int main() { ... }
: The main function where the program execution starts.int secretNumber = 7;
: Declares a variablesecretNumber
and assigns it the value 7.int guess;
: Declares a variableguess
without initializing it.do { ... } while (guess != secretNumber);
: Initiates a do-while loop that continues until theguess
matches thesecretNumber
.printf("Guess the secret number: ");
: Prompts the user to input a guess for the secret number.scanf("%d", &guess);
: Reads the user input as an integer and stores it in theguess
variable.if (guess < secretNumber) { ... } else if (guess > secretNumber) { ... } else { ... }
: Checks if theguess
is lower, higher, or equal to thesecretNumber
and provides appropriate feedback.- If the
guess
is lower than thesecretNumber
, it prints "Too low! Try again." If theguess
is higher, it prints "Too high! Try again." If theguess
matches thesecretNumber
, it prints "Congratulations! You guessed the secret number." - The loop continues until the correct
secretNumber
is guessed. return 0;
: Indicates successful termination of themain
function.