Make number guessing game using function in C.

 Number guessing game is super cool game and it is very simple to make using c language, in this game you should guess one number, if your guessed number is right then you won the game and if guessed number is false then it (program/game) asked you again to enter higher or lower number. So let’s talk about what should you know before made this game/program.

Before write this program (Game) you should know about:

  • Loop
  • If-else
  • Function
  • Conditional operator etc.
  • Generate random number in C

Before write program you should also know about:-

How to generate random number?

Random number generated using rand() function in C, you can use this function while including <stdlib>  library or if every time you want to change this random number then you should use srand(time()) function using library <time.h>.

Source code to generate random number:  


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
    int num;
      srand(time(0));
      num=rand()%100 + 1;
   printf("random number is :%d",num);
   return 0;
}

Above is source code to generate random number, now I hope so you are understand the method to generate random number in c language or without know this you can't made this game, so this is very important part of our program.

Now we should write program to make number guessing game.

SOURCE CODE OF GAME:


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void game(int);
int main(){
      int num;
      srand(time(0));
      num=rand()%100 + 1;
      game(num);
      return 0;
}
void game(int a){
      int  n,i=1;
      printf("guess a number between 1 to 100 :");
     do{
        scanf("%d",&n);
         if(n<a){
             printf("enter some higher value :");
         }
         else if(n>a){
             printf("enter some smaller value :");
         }
         else{
           
             printf("congratulation !! your guess is right, you won the game in %d attempt",i);
         }
         i++;
     }while(a!=n);
}

OUTPUT:

guess a number between 1 to 100 :55
enter some smaller value :34
enter some smaller value :23
enter some higher value :24
enter some higher value :25
enter some higher value :29
enter some higher value :30
enter some higher value :33
enter some smaller value :32
congratulation !! your guess is right, you won the game in 9 attempt

ANOTHER OUTPUT:

guess a number between 1 to 100 :67
enter some higher value :89
enter some smaller value :70
enter some higher value :75
enter some higher value :79
enter some higher value :85
enter some higher value :87
enter some smaller value :88
enter some smaller value :8
enter some higher value :86
congratulation !! your guess is right, you won the game in 10 attempt





0 Comments