Display Array Index

I'm having a bit of trouble displaying an array index with a loop, what's going on here?


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


int main()
{

char name[6] = {'j','e','r','e','m','y'};

for (int i; i == 5; i++)
{
    cout << name[i];
}


return 0;

}
You have to initialize int i. Furthermore, this second condition is wrong. You should write i <= 5.
Try: for (int i =0; i <= 5; i++)
You should initialize i as @RKint mentioned but == is not wrong and in some cases (some iterators) it's preferred than the relational operators.
It's wrong because it won't work lol
If the condition is true the loop will be executed. (while, not until)
how come it's

i <= 5

I thought that sense it start at 0 that would be true, so the loop wouldn't run.
You've got your logic inverted.

For
1
2
3
4
for (int i =0; i <= 5; i++)
{
    cout << name[i];
}


1. i is set to 0
2. tests to see if it should execute the body: as 0 is less than or equal to 5, it continues
3. calls cout << name[0]
4. then it increments i by 1 to 1
5. and goes back to step 2; this time i is 1, so it's still less than or equal to 5, it continues
6. calls cout << name[1]
7. then it increments i by 1 to 2
8. and goes back to step 2; this time i is 2, so it's still less than or equal to 5, it continues
9. calls cout << name[2]
10. then it increments i by 1 to 3
11. and goes back to step 2; this time i is 3, so it's still less than or equal to 5, it continues
12. calls cout << name[3]
13. then it increments i by 1 to 4
14. and goes back to step 2; this time i is 4, so it's still less than or equal to 5, it continues
15. calls cout << name[4]
16. then it increments i by 1 to 5
17. and goes back to step 2; this time i is 5, so it's still less than or equal to 5, it continues
18. calls cout << name[4]
19. then it increments i by 1 to 6
20. and goes back to step 2; this time i is 6, so it's no longer less than or equal to 5, so the loop breaks!


Same as

1
2
3
4
5
6
7
int i =0;

while(i <= 5)
{
    cout << name[i];
    i++;
}
Last edited on
Topic archived. No new replies allowed.