Gaurav Kumar
Gaurav Kumar

Reputation: 221

C++ for loop multiple condition inconsistency

Code in question :

#include<iostream>

using namespace std;

int main() {
    int a[10] = {0, 1, 0, 1, 0, 1, 1, 0, 0, 1};

    for (int i = 0; i < 10; ++i) if (a[i] == 1) cout<<i<<" ";

    cout<<endl;

    for (int i = 0; i < 10 && a[i] == 1; ++i) cout<<i<<" ";

    cout<<endl;

}

Output:

1 3 5 6 9
// and an empty line

If my understanding of condition evaluation is correct, then both the outputs should be the same. As the condition a[i] == 1 is checked each time, i is incremented. So, why is this happening?

I have tested this with g++ and an online ide called ideone link to code.

I believe that I am missing something very basic here and it is a very dumb issue, so please forgive me for asking this in advance.

Upvotes: 0

Views: 93

Answers (3)

Mostafa Ayaz
Mostafa Ayaz

Reputation: 478

No. The results are not the same. In the first one, the for loop scrolls over 0 to 9 and each time the inner if checks whether the corresponding index of a is equal to 1 or not. So the performance of the first one is clear. The second one acts quite different. The second for holds as long as the condition holds (while it doesn't even hold at the beginning since a[0]=0).

A better example is:

int x[]={1, 1, 1, 0, 0, 0, 0, 0, 1, 1};

the first loop prints out 0 1 2 8 9 and the second one's output is 0 1 2.

Upvotes: 0

P.W
P.W

Reputation: 26800

The condition in the for loop is evaluated before each iteration, and if it yields false, the loop is exited.

In the first case the condition is i < 10 and this becomes false only after i reaches 10, so the condition in the if is evaluated 10 times and you get the output 1 3 5 6 9.

In the second case the condition is i < 10 && a[i] == 1 which becomes false on the very first iteration when i is 0 as a[0] is 0. The for loop is then terminated and the condition in the if statement is never evaluated and so you do not get any output.

Upvotes: 1

NAM
NAM

Reputation: 13

the condition loop finish in i = 0 because a[0]=0 . your condition to continue is a[i]=1. therefore it finish in first case

Upvotes: 1

Related Questions