Guessing game. 1-1,000 but only loops twice?

I am having trouble getting this code to run. It's impossible to guess the number correctly as it only loops twice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;

int main ()
{

int guess;
char answer;

srand (time (0));
for (int i = 0; i < 1000; i++)
{

int random = rand( );
int num = ((random % 1000) + 1);


cout << "Guess a number between 1 and 1,000: ";
cin >> guess;

if (guess > num)
{
	cout << "The number is lower. Guess again:";
cin >> guess;

}
else if (guess < num)
{
	cout << "The number is higher. Guess again:";
cin >> guess;


}
if (guess == num)
{
cout << "You've guessed correctly!\n\n";
break;
}


}
return 0;

}
i moved and removed some stuff and added some comments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;

int main ()
{
int guess;
char answer;

srand (time (0));

// moved these lines out of 1000 loop.
// we want to pick random number once, not 1000 times.
int random = rand( );
int num = ((random % 1000) + 1);
cout << "Guess a number between 1 and 1,000: ";

for (int i = 0; i < 1000; i++)
{
	// stuff in here will be done 1000 times.

	// moved these lines up there.
	//int random = rand( );
	//int num = ((random % 1000) + 1);
	//cout << "Guess a number between 1 and 1,000: ";

	// one and only input guess
	cin >> guess;

	if (guess > num)
	{
		cout << "The number is lower. Guess again:";
		//cin >> guess;
		// we will get new guess when loop goes back up
	}
	else if (guess < num)
	{
		cout << "The number is higher. Guess again:";
		//cin >> guess;
		// we will get new guess when loop goes back up
	}
	else
	//if (guess == num)
	// changed this to else.
	// if guess isn't greater or less than num,
	// then it must be equal to num.
	{
		cout << "You've guessed correctly!\n\n";
		break;
	}


}
return 0;

}

have we got it yet? guess again? ahh!
Instead of a for loop, I suggest a do.. while() loop.
1
2
3
4
do
{
    //....
} while (guess != answer);
also you do not need your answer variable
Topic archived. No new replies allowed.