The below code will generate a guessing game.
#include <conio.h>
void main()
{
int x,i,j,num,count;
printf("Welcome...\nMax number of tries is 4");
count=0;
x=37; //this is the value which is to be guessed
for(i=1;i!=x;i)
{
printf("\nEnter number:");
scanf("%d",&i);
if(i>x)
printf("Too Large");
if(i<x)
printf("To Small");
count++;
if(count==4)
break;
}
if(count==4)
printf("\n\nYou lose\nnumber of tries:%d",count);
else
printf("\n\nYou win\nnumber of tries:%d",count);
getch();
}
Logic :
Store a number in an variable.This will be the hidden number.If the user enters number which is greater or smaller then the hidden number then display an appropriate message.Limit the user to fixed number of tries so that the game can end if the user is unable to guess the hidden number.
Code :
#include <stdio.h>#include <conio.h>
void main()
{
int x,i,j,num,count;
printf("Welcome...\nMax number of tries is 4");
count=0;
x=37; //this is the value which is to be guessed
for(i=1;i!=x;i)
{
printf("\nEnter number:");
scanf("%d",&i);
if(i>x)
printf("Too Large");
if(i<x)
printf("To Small");
count++;
if(count==4)
break;
}
if(count==4)
printf("\n\nYou lose\nnumber of tries:%d",count);
else
printf("\n\nYou win\nnumber of tries:%d",count);
getch();
}