Index « Previous Next »

Question

Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.

Source Code

#include <stdio.h>

int main()
{
    int num, guess, tries = 0;
    srand(time(0)); /* seed random number generator */
    num = rand() % 100 + 1; /* random number between 1 and 100 */

    printf("Guess My Number Game\n\n");

    do
    {
        printf("Enter a guess between 1 and 100 : ");
        scanf("%d", &guess);
        tries++;

        if (guess > num)
        {
            printf("Too high!\n\n");
        }
        else if (guess < num)
        {
            printf("Too low!\n\n");
        }
        else
        {
            printf("\nCorrect! You got it in %d guesses!\n", tries);
        }
		
    }while (guess != num);

    return 0;
}

Output

Guess My Number Game

Enter a guess between 1 and 100 : 60
Too low!

Enter a guess between 1 and 100 : 80
Too low!

Enter a guess between 1 and 100 : 95

Correct! You got it in 3 guesses!