1

A condition inside for loop and a same condition inside for loop block. Why these 2 gives different output?

for (i=0;i <5;i++)
{
       printf("\n");
       for (j=0;j <5;j++)
             if (i!=j)
                  printf (" i= %d j= %d ",i,j);
 }


for (i=0;i <5;i++)
{
        printf("\n");
        for (j=0;j <5 &&i!=j;j++)
               printf (" i= %d j= %d ",i,j);
  }

`

kaushikC
  • 77
  • 3

2 Answers2

0

The inner loop in the first example checks that i != j with every iteration but still iterates over all values for j in the range 0, ..., 4.

The inner loop in the second example, however, stops execution as soon as its condition

j < 5 && i != j

is false. This inner loop does not always perform 5 iterations: if i != j is true for values of j less than 5, then the loop exits early.

Greg Kikola
  • 573
  • 3
  • 6
0

They produce different outputs because the inner loops are, in no way, equivalent.

The test i != j does not affect the number of iterations on the inner loop in the first form - the number of iterations will always be 5, and the if (i != j) ... will be executed on every loop iteration.

However, in the second lot of code, i != j is now part of the loop condition, so the loop will terminate after five iterations OR the first time it finds i != j is false (i.e. if i == j).

Consider what happens in the two lots of code if i is zero.

In the first lot of code, the inner loop always iterates five times, and output is produced for all the values of j != i. For i equal to zero, this means four lines of output are produced (for j with each of values 1, 2, 3, 4 but not for 0).

In the second lot of code, with i equal to zero, i != j will be false on the first value of j (zero) so the inner loop body will never be executed - and the loop body will not be executed for subsequent values of j. No output will be produced.

Peter
  • 35,646
  • 4
  • 32
  • 74