How to write a number guessing game in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand((unsigned int)time(NULL));

    unsigned int num = rand() % 10;
    printf("Guess the number (0 - 9)\n\n");

    while (1) {
        unsigned int usernum;
        printf("Enter your Guess: ");
        scanf("%d", &usernum);

        if (num == usernum) {
            printf("You got it!");
            break;
        }
        else if (num > usernum) {
            printf("The number is greater than %d. Try Again!\n\n", usernum);
        }
        else {
            printf("The number is smaller than %d. Try Again!\n\n", usernum);
        }
    }

    return 0;
}




/*
run:

Guess the number (0 - 9)

Enter your Guess: 5
The number is greater than 5. Try Again!

Enter your Guess: 7
The number is greater than 7. Try Again!

Enter your Guess: 9
The number is smaller than 9. Try Again!

Enter your Guess: 8
You got it!

*/

 



answered Mar 2, 2023 by avibootz
...