if-else if issue

Uhm I encountered a weird error that happened within these 2 codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int step = 1;
for(int i = 0; i < n; i++)
    {
        //cout << step << " ";
        if(step == 1)
        {
            sumA += a[i];
            step++;
        }
        else if(step == 2)
        {
            sumB += a[i];
            step++;
        }
        else if(step == 3)
        {
            sumC += a[i];
            step = 1;
        }
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int step = 1;
for(int i = 0; i < n; i++)
    {
        cout << step << " ";
        if(step == 1)
        {
            sumA += a[i];
            step++;
        }
        if(step == 2)
        {
            sumB += a[i];
            step++;
        }
        if(step == 3)
        {
            sumC += a[i];
            step = 1;
        }
    }


The first code increments step correctly while the 2nd code keeps step = 1 ALL THE TIME, why is that happening?
Last edited on
In the second example, there are separate if statements that all get evaluated.

line 1 - step is 1
line 5 - step == 1 is true, so line 8 - step is incremented to 2
line 10 - step == 2 is true, so line 13 - step is incremented to 3
line 15 - step == 3 is true, so line 18, step is back to 1
back to line 4, step is 1
Last edited on
Topic archived. No new replies allowed.