Search code examples
cfor-loopnested-loopscontinue

continue statement inside nested for loop


I don't understand what exactly does the continue statement inside this for loop do. How is code any different if I remove it? Which lines does it skip if it's placed at the end of for loop?

int sum = 0, i, j, stop = 0;
for( i = 1; i <= 5 && !stop; i++)
{
    for( j = 1; j <= 5 ; j++)
    {
        if (j%4 == 0)
        {
            stop = 1;
            continue;
        }
        sum += i+j;
    }
}
printf("%d\n", sum);

If you run this program the sum is going to be 15, and if you comment out countinue line then it's going to be 20.


Solution

  • It would be more clear if you would format the code. Let's consider the inner loop

    for( j = 1; j <= 5 ; j++)
    {
        if ( j % 4 == 0)
        {
            stop = 1;
            continue;
        }
    
        sum += i+j;
    }
    

    Thus as you see if j % 4 == 0 then statement

    sum += i+j;
    

    is skipped.

    As for the code in whole then it has no any sense.:) It is a silly code.

    In fact your code is equivalent to the following

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

    So you will get sum 2 + 3 + 4 + 6 that is equal to 15.:)