Guess the Number C Game Program

In this tutorial we are writing Guess the Number C Program.

First the program will print that it has a number in its mind, and the user have to guess it.User have infinite chances for guessing the right number.

In c language rand function is used for getting random numbers. To make sure that we get different sequence of random numbers for separate runs, we use srand function and pass the system time in seconds using time function.

To use rand and srand functions, we need to include stdlib header file and for getting time using time function we need to include time.h header file.

Program Source Code : guess_the_number.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 
 5 int main()
 6 {
 7 
 8     int mynum, usernum;
 9 
10     srand(time(NULL));
11     mynum = rand() % 10;
12 
13     printf("I have a number in mind (0 - 9). can you Gues it?\n");
14 
15     while (1)
16     {
17         printf("Enter your Guess : ");
18         scanf("%d", &usernum);
19 
20         if (mynum == usernum)
21         {
22             printf("Yes you got it!");
23             break;
24         }
25         else if (mynum > usernum)
26         {
27             printf("My number is greater than %d. Try Again!\n\n", usernum);
28         }
29         else
30         {
31             printf("My number is smaller than %d. Try Again!\n\n", usernum);
32         }
33     }
34 
35     return 0;
36 }

Program Output : Run 1

I have a number in mind (0 - 9). can you Gues it?
Enter your Guess : 6
My number is greater than 6. Try Again!

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

Enter your Guess : 7
Yes you got it!

Video Tutorial : Guess the Number C Game Program

Video Tutorial : How to generate Random Numbers in C Programming language

Video Tutorial : Generate Random Numbers between a range of numbers