In: Computer Science
C++
The program implements the Number Guessing Game. However, in that program, the user is given as many tries as needed to guess the correct number.
Rewrite the program so that the user has no more than five tries to guess the correct number.
Your program should print an appropriate message, such as “You win!” or “You lose!”.
Code:
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<random>
using namespace std;
int main()
{
int i,tries=5,userGuess=0;/*Declaring variables*/
srand(time(0));
int num;/*Generating random number from 1 to 10*/
num=rand()%(10)+1;
for(i=0;i<tries;i++)
{/*This loop iterated 5 times 0 to 4 that means 5 tries*/
cout<<"Guessn a number from (1-10):";
cin>>userGuess;
/*Rading user guessed number*/
if(userGuess==num)
{/*If user guesses corectly*/
break;
}
else
{/*If user doesn't guess correct*/
cout<<"Wrong Guess Try Again"<<endl;
}
}
if(i==tries)
{/*After the loop if the loop iterate 5 times that means
user didn't guess correct*/
cout<<"You Lose!";
}
else
{
/*If he guessed correctly*/
cout<<"You Win!"<<endl;
}
}
Output:
Indentation:
The code below will tell the user if the number is too high or too low
Code:
#include<iostream>
#include<random>
using namespace std;
int main()
{
int i,tries=5,userGuess=0;/*Declaring
variables*/
int num=rand()%(10)+1;/*Generating random number from
1 to 10*/
for(i=0;i<tries;i++)
{/*This loop iterated 5 times 0 to 4 that means 5
tries*/
cout<<"Guessn a number from
(1-10):";
cin>>userGuess;
/*Rading user guessed
number*/
if(userGuess==num)
{/*If user guesses corectly*/
break;
}
else if(userGuess>num)
{
cout<<"Your Guess is Too High Try again"<<endl;
}
else if(userGuess<num)
{
cout<<"Your Guess is Too Low Try again"<<endl;
}
}
if(i==tries)
{/*After the loop if the loop iterate 5 times that
means
user didn't guess correct*/
cout<<"You Lose!";
}
else
{
/*If he guessed correctly*/
cout<<"You
Win!"<<endl;
}
}