for Loop Issue

OK, still working on:
http://www.cplusplus.com/forum/articles/12974/

I am all the way up to the fourth exercise, Pancake Glutton. Everything works. My program takes input for each of ten gluttons. It outputs the number of pancakes eaten by each. Here's the issue. On the last iteration of the display loop, (making an assumption that it is in the display loop), it adds one to the number of pancakes the last glutton eats.

I am on a Windows Vista Home Premium machine with Code::Blocks 10.05 rev 6283.

Here's my code.

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

int getPancakesEaten(int);

int main()
{
    //Declare array
    int gluttons[9];

    //Get values
    for (int counter = 0; counter < 10; counter++)
    {
        gluttons[counter] = getPancakesEaten(counter);
    }

    //Display results
    cout << setw(10) << "Glutton:" << setw << "#of pancakes" << endl;
    for (int counter = 0; counter < 10; counter++)
    {
        cout << setw(10) << counter + 1<< setw(10) << gluttons[counter] << endl;
    }
}

int getPancakesEaten(int counter)
{
    int numPancakes;
    cout << "Enter the number of pancakes eaten by glutton number " << counter + 1<< ":" << endl;
    cin >> numPancakes;

    return numPancakes;
}
Your for loop starts at 0 and goes to 9, that's 10 objects. You are using an array of 9 objects. You are overflowing your buffer.
Just discovered issue number 2. In testing, to get through all ten data inputs I just entered the number 1 ten times. If I do that, it goes back and starts asking for input starting with glutton #3 again.

The issue occurs, apparently, if I enter the number 1 on glutton #10.
You have to do this exercise using only arrays, logic (if, switch), and loops (while, do, for). No functions allowed :)

I don't think yuo need more than one array for number of pancakes eaten and 2 for loops, one to get numbers from user and a second to display them.

And then you can get the max and min using if....
sebgar,
Removing the function resolved both issues. I'm just baffled as to why.

ultifinitus,
I thought that the number in the array declaration was the upper bounds of the index, not the number of objects in the array. I guess it's time for me to read that section of the book again.

Thanks to both of you.
Topic archived. No new replies allowed.