Simple array problem

Hello guys. I am currently understanding arrays, and then I encountered a problem. Why is it that when I compile & execute this program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    double length[] = {32.45, 54.56, 32.45, 92.00, 5.29};
    int index = sizeof(length) / sizeof(double);
    cout<<"Array members: "<<endl;
    for(int i = 0; i < index; ++i)
            cout << "Length : " << i + 1 << length[i] << endl;    
    system("PAUSE");
    return EXIT_SUCCESS;
}


It shows me:
Array members:
Length: 132.45
Length: 254.56
Length: 332.45
[...]

And not

Array members:
Length 1: 32.45
Length 2: 54.56
Length 3: 32.45
[...]



Thanks in advance.
Short answer: Because that's what you're telling it to do.

You'd need to change line 12 to:

cout << "Length " << i+1 << ": " << length[i] << endl ;

to achieve that.

Edit: i+i was a typo.
Last edited on
Thanks! It makes sense.

cout << "Length " << i+i << ": " << length[i] << endl ;

But isn't this +i unnecessary? Seems like it makes the output do multiplications of 2's (in Length x: ) instead of counting 1's.
I think that's probably a typo. Should be i+1.
Topic archived. No new replies allowed.