Thursday 17 October 2013

Continue Statement in C Programming

Continue Statement

(continue statement in c, continue statement in java, continue statement python, continue statement php, continue statement in c programming)


There is another statement relating to loops. This is the continue statement. Sometimes we have a lot of code in the body of a loop. The early part of this code is common that is to be executed every time (i.e. in every iteration of loop) and the remaining portion is to be executed in certain cases and may not be executed in other cases. But the loop should be continuous. For this purpose, we use the continue statement. Like the break statement, the continue statement is written in a single line. We write it as
                        Continue;
 The continue forces the immediate next iteration of the loop. So the statements of the loop body after continue are not executed. The loop starts from the next iteration when a continue statement is encountered in the body of a loop. One can witness very subtle things while using continue.
Consider the while loop. In while loop, we change the value of the variable of while condition so that it could make the condition false to exit the loop. Otherwise, the loop will become an infinite one. We should be very careful about the logic of the program while using continue in a loop. Before the continue in a loop. Before the continue statement, it is necessary to change (increment/decrement) the value of the variable on which the while condition depends. Similarly it is same with the do-while loop. Be careful to increment or decrement the conditional variable before the continue statement.
In for loop, there is a difference. In a while loop when continue is encountered, the control goes to the while statement and the condition is checked. If condition is true the loop is executed again else the loop exits. In a for loop, the three things i.e. initialization, condition and increment/decrement are enclosed together as we write
for (counter_variable = 0;  counter_variable <=5; counter_variable++).

In the for loop when a continue is encountered, the counter_variable (i.e. loop variable) is incremented at first before the execution of the loop condition. Thus, in for loop the increment to the loop variable is built in and after continue the next iteration of the loop is executed by incrementing the loop variable. The condition is checked with the incremented value of the loop variable. In while and do-while loop, it is our responsibility to increment the value of the loop variable to test the condition. In a for loop, the continue automatically forces this increment of value before going to check the condition. 

No comments:

Post a Comment