Oct 7, 2020

Guess the number game in C (project 1)

Ex: Write a C program to make a game, guess the number. How to write a C program using rand function  to make a (guess number) game. C game for guess the number.


Quick links:



In these program we used two extra header files one is <stdlib.h> and second is <time.h>. <stdlib.h> header file  used because in the program we have used srand() function and rand() function. This two functions are defined in <stdlib> header file.

<time.h> header file used because in the program we have used time() function.  time() function gets current system time as a structure.





Program:


#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main()

{

int num;

int guess=1;

int rand_num;

/*For random numbers between 1 to 100*/

srand(time(0));

rand_num = rand()% 100 + 1;

/*Run a loop until the number is guessed*/

       do{

printf("Enter the number between 1 to 100:\n");

scanf("%d",&num);

if(num>rand_num)

               {

                    printf("Enter lower number\n");

               }

            else if(num<rand_num)

               {

                     printf("Enter larger number\n");

                }

             else

               {

                     printf("You guessed number in: %d attempts\n",guess);

               }

     /*Increment guess by 1*/

    guess++;

}while(num!=rand_num);

return 0;

}


Above program shows the following output:




Share This:    Facebook Twitter

0 comments:

Post a Comment

If you have any doubts, please discuss here...