Select Page

[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]

## “Guessing a Number” – game in C++, making it little more interesting!!

### Introduction – Why this game?

Guess a Number – The main objective has been to improve your logic – around loops and conditional statements. This number guessing game is quite old and you might just find similar programs floating around on the internet. I tried to create something that gives enough clues to guess a number but at the same time guessing a number might not be that easy.

First of all, unlike other programs it uses random() function to generate a new number every time between 100 and 200 and then depending upon how far you are from that number it gives you some clues. When you are too close it tells you that but doesn’t specify your number is smaller or greater than that number.

To be precise, it is not at all difficult to guess a number, its just to make it more interesting. More over , I expect from my students to create a new version of their own of this game having little more twists and turns.

Enjoy the code below:[/vc_column_text][vc_column_text]

```//Including required header files
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{

clrscr();
int secretno,L=100,U=200,gno,diff;
randomize();
secretno=random(U-L)+L;      // formula for generating a random number between L (100) and U(200)
cout<<secretno;
cout<<"\nGuess a no (Its between 100 and 200) and 0 to Give UP!!: ";
cin>>gno;
diff=secretno-gno;
cout<<endl<<diff;
while(gno!=0)
{
if(diff==0)
{
cout<<"\nYES!! You did it!! Correct.";
break;
}
else if(diff>0)
{
if(diff<=7)
{
cout<<"\nYou are almost there.";
}
else if(diff<20)
{
cout<<"\nSmall. Quite Close, but not there";
}
else if(diff<50)
{
cout<<"\nQuite Small";
}
else if(diff<75)
{
cout<<"\nSMALL. Huge difference";
}
else
{
cout<<"\nSeems you are at other end";
}
}
else
{
diff=diff* -1;
if(diff<=7)
{
cout<<"\nYou are almost there.";
}
else if(diff<20)
{
cout<<"\nBig. Quite Close, but not there";
}
else if(diff<50)
{
cout<<"\nQuite Big";
}
else if(diff<75)
{
cout<<"\nBIG. Huge difference";
}
else
{
cout<<"\nSeems you are at other end";
}
}
cout<<"\nGuess the no again (100 to 200) nd 0 to Give UP!!: ";
cin>>gno;
diff=secretno-gno;
}
getch();

}```

[/vc_column_text][/vc_column][/vc_row]