Wednesday, August 7, 2013

Number guessing game in C++

Today we are going see how we can make a number guessing game in C++.

To start with first u will need to have a text editor or simply notepad will do and a C++ compiler will do.

So first we are going to see what actually we need to do in the program.

Here we have to give user three chances to guess a number which and if the number matches the one with that already defined then it should print "You won" or else it should print "You lost"

--> so will start with the code....

   #include
   #include

these are the two header files which we need to call to run the program.

  void main()
 {
 clrscr();

here we are starting the main function.

  int n=10;
  int g,c=1;

here we have declared three variables n is the no which the user has to guess, g is for taking the value from the user and c is the no of chances.

  while(c<=3)
  {
  if(c==1)
  {
   cout<<"\n First Chance";
   }
   else if(c==2)
  {
   cout<<"\n Second Chance";
   }
   else
   {
    cout<<"\n Play Carefully!!! Last Chance";
    }

   cout<<"\n Enter the guess...";

   cin>>g;

   if(g==n)
  {
  cout<<"\n Congratulations!!! You have won";
  break;
  }
  else
 {
 cout<<"\n Better Luck Next Time";
 }
 c++;
 }
 getch();
 }

the body of the code checks the no whether the no entered by user is correct or not if it is correct it prints you won else it repeats till three chances and then ends printing you lose.