# Answer to Question #71576 in C++ for m

Question #71576

Write a code that will calculate randomly a number between 1 and 10 (without displaying it) and will ask the user to guess it. If the user answers correctly, the program prints “Good” and add 1 to his score, if not, the program prints “sorry”, gives the correct answer, then selects another number. After 10 consecutive games, the programs stops and prints the final score. Hint: use a random buitin function (rand) and write the #include <stdlib.h> at the beginning.

your guess? 7 Sorry, answer was 5 your guess? 6 Sorry, answer was 0 your guess? 3 Sorry, answer was 1 your guess? 9 Sorry, answer was 0 …..

your guess? 1

Sorry, answer was 5

your final score is 0

using while,for,array if possible

your guess? 7 Sorry, answer was 5 your guess? 6 Sorry, answer was 0 your guess? 3 Sorry, answer was 1 your guess? 9 Sorry, answer was 0 …..

your guess? 1

Sorry, answer was 5

your final score is 0

using while,for,array if possible

Expert's answer

#include <iostream>

#include <cstdlib>

#include <ctime>

int main()

{

srand(time(0));

int correctAnswer = 0;

for (int i = 0; i < 10; ++i)

{

int randNumber = rand() % 10 + 1;

std::cout << "your guess?: ";

int userChoice = 0;

std::cin >> userChoice;

if (randNumber == userChoice)

{

std::cout << "Yes! You guessed number!" << std::endl;

correctAnswer++;

}

else

{

std::cout << "Sorry, answer was " << randNumber << std::endl;

}

}

std::cout << "your final score is " << correctAnswer << std::endl;

}

#include <cstdlib>

#include <ctime>

int main()

{

srand(time(0));

int correctAnswer = 0;

for (int i = 0; i < 10; ++i)

{

int randNumber = rand() % 10 + 1;

std::cout << "your guess?: ";

int userChoice = 0;

std::cin >> userChoice;

if (randNumber == userChoice)

{

std::cout << "Yes! You guessed number!" << std::endl;

correctAnswer++;

}

else

{

std::cout << "Sorry, answer was " << randNumber << std::endl;

}

}

std::cout << "your final score is " << correctAnswer << std::endl;

}

Need a fast expert's response?

Submit orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment