Need to stop the loop at a certain point

I have an Array where 10 people eats pancakes. I want to stop the input when the last person have eaten but it needs Another input to stop the loop and I cant figure it out.

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
 #include <iostream>

using namespace std;

// Constants
const int PERSONS = 10;

int main()
{

	int pancakes[PERSONS];

	int i = 0;
	int numOfElements = 0;
	int input;

	cout << "Please type in how many pancakes the persons have eaten: ";
	cin >> input;

	while (i < PERSONS)
	{
		numOfElements++;
		pancakes[i] = input;
		i++;
		cin >> input;
		if (i == (PERSONS - 1))
		{
			cout << "Thank you!" << endl;
		}
	}

	for (int j = 0; j < numOfElements; j++)
	{
		cout << "Person #" << (j + 1) << " ate " << pancakes[j] << endl;
	}

	return 0;
}
Last edited on
does this while (i < PERSONS) not stop when the 10th person has eaten?
Why do you have if(i == (PERSON -1)), thats the job of the while loop
Last edited on
when I have typed in ten values the loop requires another cin to start the for-loop to print the values. Therefor the if-loop.

DonĀ“t know how to print the values without the eleventh cin-input.
Try moving the cin >> input on line 18 to the first line inside the loop and eliminate lines 25-29. You can put your thank you message immediately after the while loop.

I see no need for the variable numOfElements. As it now stands it will always be the same as PERSONS when the while loop completes, so you can just use PERSONS in your for loop condition on line 32 instead of numOfElements.

1
2
3
4
for (int j = 0; j < PERSONS; j++)
{
	cout << "Person #" << (j + 1) << " ate " << pancakes[j] << endl;
}

Last edited on
Topic archived. No new replies allowed.