Search code examples
cnested-loops

Nested for loops with initialization outside the loop


#include <stdio.h>

int main()
{
    int i = 1, j = 1;

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

The above code runs the outer for loop only once. The output being :

1 - 1
1 - 2
1 - 3
1 - 4
1 - 5

But when I make the following change, the printfs get printed the expected 25 times.

    for(i=1; i<=5; i++)
    {
        for(j=1; j<=5; j++)
        {
            printf("%d - %d\n",i, j);
        }
    }

Can someone please explain this behavior?


Solution

  • Simple in the second iteration of i(when i=2) the value of j is 6 so the second (the nested one) for never runs. But in the second case at each iteration of i , j is initialized to 1.