How to create Number guessing game in C
Notes:
How to create Number guessing game in C Programming Language :
When to use do while loop:
- when we want to execute set of statements at least once; we use do while loop
- do while loop is used to create menu system, game loop etc.
- To understand when to use do while loop we code guess the number game using do while loop in c programming language.
Ex: Creating guess the number game using do while loop in C
srand(unsigned int):
- initializes the randomizer based on the given integer number
time(NULL):
- returns the current time in seconds
srand(time(NULL));
- initializes the randomizer based on the current time
rand();
- based on the initialized randomizer; it generates a random number between 0 and maximum possible random number
rand() % 10:
- generates a random number between 0 and 9
(rand() % 10) + 1:
- generates a random number between 1 and 10
Example Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int randomNumber =0;
int num =0;
char ch = 'y';
printf("Welcome to Guess The Number Game !!!\n");
do
{
srand(time(NULL));
randomNumber = (rand() % 10) + 1;
printf("\n");
printf("Guess the number between 1 to 10:");
scanf("%d",&num);
if(randomNumber == num)
{
printf("You Won!\n");
}
else
{
printf("You lost! The number is = %d\n",randomNumber);
}
printf("\n");
printf("Do you want to replay? (y/n):");
scanf(" %c",&ch);
}while(ch=='y');
printf("\n\n");
printf("You played awesome\n");
printf("See you Nexttime\n");
getch();
return 0;
}