1

I can't figure out what I did wrong. I want to print non-zero elements and the below code prints none.

#include <stdio.h>

int main ()
{
    int arr[4] = { 0, 3, 0, 7 };
    // print non zero elements
    for (int i = 0; i != 4 && arr[i] != 0; ++i)
        printf("%d\t%d\n", i, arr[i]);
}

But if I move the array test like the below, it works:

#include <stdio.h>

int main ()
{
    int arr[4] = { 0, 3, 0, 7 };
    // print non zero elements
    for (int i = 0; i != 4; ++i) {
        if (arr[i] != 0)
           printf("%d\t%d\n", i, arr[i]);
    }
}

What's wrong?

1
  • I think you got it now. Commented Jul 20, 2015 at 2:25

3 Answers 3

6

The reason the first loop is different from the second loop is that the first loop quits as soon as i reaches the position of the first zero in the array, while the second loop always goes all the way up to the forth element.

Your first loop is equivalent to this:

for (int i = 0; i != 4; ++i) {
    if (arr[i] != 0)
       printf("%d\t%d\n", i, arr[i]);
    else
        break;
}

Breaking on seeing zero is what makes the first loop to terminate early.

Sign up to request clarification or add additional context in comments.

2 Comments

why would it quit for the first zero in the array? this is not a while loop.
@BestCoderEver The form of the loop doesn't matter: for loop is just like a while loop, but it has two more "compartments" in the loop header - for initialization, and for advancing loop variable. The loop condition in a for loop is the same as the "continuation condition" of a while loop. In your case, that's i != 4 && arr[i] != 0, so your loop would stop at the first zero.
2
for (int i = 0; i != 4 && arr[i] != 0; ++i)

The loop instantly terminates if arr[i] == 0. Ans as the first element already is 0, it is not even run once.

Comments

2

The reason is your first for loop is equivalent to this:

int i=0;
while(i!=4&&arr[i]!=0)
{
  printf("%d\t%d\n", i, arr[i]);
  ++i;
}

That is the condition is being checked in the beginning and therefore your loop terminates before it can begin its first iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.