For Loops in an Array Comprehension Help

Hi guys, I encountered this problem while I was tackling loops in an array. Can someone help me by explaining to me how do I get the number 1 in the output? Because while I'm understanding it, it is 3 5. I just got a little confused when an array is combined with a looping statement.
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
//The output is 1 3 5
//The output that always comes in my mind always come out in 3 5
//Help me by explaining it on how the output became 1 3 5

#include <iostream>

using namespace std;

int main()

{

    float ARRAY[] = {1,2,3,4,5};

    for (int a = 0; a<5; a++)

    {

        cout  << ARRAY[a] << " ";

        a++;

    }

}
Last edited on
So without the 2nd a++ at line 21, you do understand why you see 1 2 3 4 5 right?

Simple debugging - add some more cout statements to see the values of other variables.
1
2
3
4
5
6
    for (int a = 0; a<5; a++)
    {
        cout << "DEBUG:subscript=" << a << endl;
        cout  << ARRAY[a] << " ";
        a++;
    }

It's called software for a reason, you can change any of it at any time for any reason.
One reason being, "I'm confused", so add something that might resolve confusion.
You can just as easily remove it again when you're less confused.

Or use a debugger

$ gdb -q ./a.out
Reading symbols from ./a.out...
(gdb) break 20
Breakpoint 1 at 0x12aa: file foo.cpp, line 20.
(gdb) run
Starting program: a.out 
DEBUG:subscript=0

Breakpoint 1, main () at foo.cpp:20
20	        cout  << ARRAY[a] << " ";
(gdb) print a
$1 = 0
(gdb) c
Continuing.
1 DEBUG:subscript=2

Breakpoint 1, main () at foo.cpp:20
20	        cout  << ARRAY[a] << " ";
(gdb) print a
$2 = 2
(gdb) 


After figuring out how to use the editor and compiler, learning even simple things in the debugger like
- breakpoints
- printing variables
- single stepping
will be extremely useful.
Topic archived. No new replies allowed.