continue statement inside nested for loop
Solution 1
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.:)
Solution 2
The continue
statement is used to start the next iteration of a loop,skipping everything in the loop,after the continue
. In your case,once the execution of the program reaches the continue
statement,then the next iteration of your inner loop starts,skipping whatever there was after the continue
. It skips sum += i+j;
as it is after the continue
and the sum will not be added when j
is 4 as j%4
will be 0. This is why you get 20 when you comment the continue
and 15 when you uncomment it.
P.S: Your outer loop will execute only once as stop
will be changed inside the if
in your inner loop.
Solution 3
The continue statement skips the remainder of the current loop. In the case of nested loops, it skips to the next iteration of the innermost loop.
In this case, if you didn't continue, you would execute sum += i+j;
in every iteration, where it appears you only want it sometimes.
That being said, this is a very awkward loop to begin with. The whole stop
variable is rather ill conceived from the get-go anyway.
Firmus
Updated on May 25, 2020Comments
-
Firmus almost 4 years
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.
-
Mawg says reinstate Monica over 9 yearsand the I loop has no porpoise, since it will only loop once