C Exercises

Oct 7, 2020

Guess the Number Game in C (Project 2)

Guess the number game Program in C:

In this tutorial we will learn how to create Guess the number game project in C.


  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.



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.


#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:


Guess the number game project in C


I hope you like it.... visit our another game project in C article.


No comments:

Post a Comment

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