The continue statement interrupts the current step of a loop and continues with the next iteration. We do this, for some particular case, when we don’t want to execute the entire body of the loop, but still we want to go through the rest of the iterations.
Do you learn better from video?
Learn faster with deeper understanding! |
This is for contrast of the break statement which stops the execution of the loop and transfers the control to the first line after the loop.
Continue:
Let's print all capital letters from A to G, with the exception of E.
char
letter;
for(letter
= 'A'; letter <= 'G';
letter++)
{
if(letter
== 'E')
continue;
printf("%c",
letter);
}
When we use nested loops we will interrupt only the body of the inner-most loop that surrounds the statement.
while(...)
{
//body of the outer loop
for(...)
{
//body of the inner loop
if(...)
continue;
}
}
Here we will interrupt only the current execution of the for loop and transfer control to the next iteration of the for loop.
In the next example, continue is not part of the inner loop. When the “if” is true, we stop the execution of the while’s body and skip the entire for loop. The next iteration over the while will execute normally, including the inner loop.
while(...)
{
//body of the outer loop
if(...)
continue;
for(...)
{
//body of the inner loop
}
}
In practice the continue statement is rarely used. If you write code regularly, eventually you will need it at some point, but not as frequently as the break statement.
Related topics:
Do you learn better from video?
Learn faster with deeper understanding! |
Did this help? Support me with your vote ;-) |
|
|
Did this help? |
|
|