#include <stdio.h> #include <stdlib.h> int main() { int number, guess, tries = 0; number = rand() % 100 + 1; // Generate a random number between 1 and 100 printf("Guess the number between 1 and 100!\n"); do { printf("Guess: "); scanf("%d", &guess); tries++; if (guess > number) { printf("Too high! Try again.\n"); } else if (guess < number) { printf("Too low! Try again.\n"); } else { printf("Congratulations, you guessed the number in %d tries!\n", tries); } } while (guess != number); return 0; }
This code includes the standard input/output library <stdio.h> and the standard library for generating random numbers <stdlib.h>. The main function declares three integer variables: number, guess, and tries, which are initialized to 0. The program generates a random number between 1 and 100 using the rand() function and assigns it to the number variable. It then prompts the user to guess the number by printing a message using printf(). The program then enters a do-while loop that continues until the user guesses the correct number. In each iteration of the loop, the program reads the user's guess using scanf(), increments the tries counter, and compares the guess to the generated number using if-else statements. If the guess is too high or too low, the program informs the user to try again. When the user guesses the number correctly, the program prints a congratulatory message with the number of tries it took and exits the loop.