Number Guessing Game in C
Hello everyone, in this article we are going to make a simple Number Guessing game in C language. Program will generate a random number and user will try to find the generated number.Let's get started.
In this article we are going to make some extra things. Normal we can create the number witn rand() method directly but in here we are going to add some specification.
Purpose of this example is to show how can we make some configurations on selected numbers. So in here we are going to create 4-digit number with different digits and could not be started with zero. This is just a simple example and you can cusstomize it according to your requirements.
Now lets start then :)
First we have to add stdio library to control inputs and outputs before:
#include <stdio.h>
Be careful, After this point all methods will be inside of int main( void ) { ... } function.
Firstly we need to set the randomise on time base else program will always generate same numbers
time_t t;
srand((unsigned) time(&t));
Here our digits array and the variable which hold the generated number
int digits[4];
int generated_number = 0;
for(int i = 0 ; i < 4 ; i++ ) {
int adding_ok = 1;
int digit = rand() % 10;
for(int j=0; j < i; j++)
{
if( (digit == digits[j]) )
{
adding_ok = 0;
i--;
}
if(adding_ok == 1 && (i == 0 && digit == 0 )) // ilk sayi sifir olamaz diyoruz
{
adding_ok = 0;
i--;
}
}
if(adding_ok == 1)
digits[i] = digit;
}
Until here our digits are ready and now we need to create the number with these digits. Below formulation will accomodate this requirement:
generated_number = (digits[0] * 1000) + (digits[1] * 100) + (digits[2] * 10) + (digits[3] * 1);
Now game section is starting :) Let's have some fun :)
Here we have essential variables to hold the input data and its integer value Also I have incorrect entry counter variable.
char * str[100];
int entered_number = 0;
int incorrect_counter = 0;
while(1)
{
printf("Guess Number : ");
fgets(str, sizeof(str), stdin);
entered_number = atoi(str);
if(entered_number == generated_number)
{
printf("You guessed Correct...\n");
break;
}
else
{
if(entered_number > generated_number)
{
printf("Go Down: \n");
incorrect_counter++;
}
else if(entered_number < generated_number)
{
printf("Go up : \n");
incorrect_counter++;
}
}
if( incorrect_counter >=10)
{
printf("Failed ...\n");
printf("Generated Number : %d\n", generated_number);
printf("Game over ...\n");
break;
}
}
That is all in this article.
You can reach the example file on Github via : https://github.com/thecodeprogram/TheSingleFiles/blob/master/number_guessing_game_in_c.c
Burak Hamdi TUFAN
Comments