Josey - 1 year ago 126
C++ Question

# For loop - Magic number program

What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly.

``````#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>

using namespace std;

int main()

{

int magic; // This is a random number between 1 and 20

int guess; // This is the guess number being attempted (up to 3 guesses)

int magicguesses; // This is the amount of magic numbers being guessed attempted

int i;

int number; // This is the number the user guessed

bool numberismagic = false; // This is the flag variable

unsigned int seed;

seed = time(NULL);

srand(seed);

magic = rand() % 20 + 1;

cout << "How many magic numbers would you like to guess at today?\n";

cin >> magicguesses;

for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;

for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;

cout << "Guess a number between 1 and 20:" << endl;

cin >> number;

while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";

cin >> number;

cout << endl;
}

if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";

numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";

if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}

if (number != magic)
cout << "The magic number is:" << magic << endl;
}

return 0;
}
``````

I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable `magic` inside the first `for loop` so the magic number changes after the user guesses correctly or they run out of tries.
``````for (i=1;i<magicguesses+1;i++)