In: Electrical Engineering
this has to be coded in c ++
• Write a program which generates a DIFFERENT random number between
1 and 100 everytime you run the program. Please go online and see
how poeple are trying to
solve this. You can submit their code. Make sure you include a
comment which shows
from where the code was taken. You do not need to understand the
code but if you
can, thats great. This program will be used in the upcoming labs so
you are strongly
encouraged to do it now so that you can use it later.
• Using the code from Part 1, play a game where you have to guess
the random number
generated. When the user makes an incorrect guess, print a message
which says that
you either guessed too low or too high. The user gets a total of 5
chances to guess
the number. If the user manages to guess the number within 5
chances, then print a
message saying that the user won the game and took %d chances
c++ code
#include <iostream>
#include <cstdlib>
using namespace std;
void game(int rand_num)
{
for (int i=0;i<5;i++){
int choice;
cout<<"Enter your guess "<<endl;
cin>>choice;
if(choice ==rand_num){ // if choice matches
cout<<"User Won the game in "<<i+1<< "chances" <<endl;
break;
}
else
{
if(rand_num>choice)
{
cout<<"you guessed low" <<endl; //to check the condition
}
else
{
cout<<"you guessed high"<< endl;
}
}
}
}
int main()
{
int number= (rand() % 100) + 1; //will generate random numbers 0-99 and then scaled to 0-100 by +1
game(number);
cout<<"Actual number is "<<number;
return 0;
}
OUTPUT
NOTE: Rand() can generate any number but sometimes generates number in a compiler .