Repeating?

I would like my program to repeat but I dont know how to use a loop with this (because my brain only knows how to use numbers and loops.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
using namespace std;

int main(){
	srand((unsigned)time(0));
	int random_integer;
	for(int index=0; index<20; index++){
		random_integer = (rand()%5)+1; 
	}
	char move;
	cout << "Would you like to go left, right, up, or down?(l,r,u,d)";
	cin >> move;
	if (move == 'l' || move == 'r' || move == 'u' || move == 'd')
	{
   		if (random_integer > 4)
		cout << "You got a apple" << endl;
   		else
		cout << "You found nothing" << endl;
	}
	else cout << "Bye Bye." << endl;
}


I would like it to repeat before the part that says bye bye.
Thanks but when I run it it seems to just make one random number and use that one I want it to generate a new number each time.

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
#include <iostream>
#include <cstdlib>
using namespace std;

int main(){
	srand((unsigned)time(0));
	int random_integer;
	for(int index=0; index<20; index++){
		random_integer = (rand()%50)+1; 
	}
	char move;
	do {
		cout << "Would you like to go left, right, up, down, or quit?(l,r,u,d,q)";
		cin >> move;
		if (move == 'l' || move == 'r' || move == 'u' || move == 'd')
		{
   			if (random_integer > 4)
			cout << "You got a apple" << endl;
   			else
			cout << "You found nothing" << endl;
		}
		else cout << "Bye Bye." << endl;
	} while (move != 'q');
	return 0;
}
Then seed the random function inside the loop...? My bad, read below.
Last edited on
Your for loop (lines 8-9) are your problem. At the moment you are simply changing the value of random_integer 20 times before moving into your do while loop. You need to assign a value to random_intger everytime you iterate through your do-while loop. Note however, that you should only call srand() once.

Also, have you realised that in your first post you have: random_integer = (rand()%50)+1;

Wheras in your second you have: random_integer = (rand()%5)+1;
Topic archived. No new replies allowed.