Page 338 - Web Applications (803) Class 11
P. 338
Let us try to understand this example. The variable ‘i’ is initialised with the value 1. Since 1 is not divisible by 3, the if
condition turns out to be false and so the else block is executed—“The number is 1” is displayed on screen. The same
happens when i=2.
Now, when ‘i’ takes the value 3, then the if condition turns true. So, break statement causes the control to “jump
out” of the loop (causing loop termination) and control reaches the document.write statement outside the loop. This
statement is then executed. Hence, only 2 numbers are displayed.
Let us now understand the ‘continue’ statement. A continue statement stops the execution of the current iteration
of the loop if a specific condition occurs and sends the control of the program to the beginning of the loop for next
iteration. It skips the execution of rest of the statements of the loop for the current iteration. The syntax of the continue
statement is same as the break statement.
Example:
<HTML>
<BODY text="blue”>
<H2 style="color:red;">Using a loop with a continue statement.</H2>
<SCRIPT>
for(i=1;i<10;i++) {
if (i%3==0)
{ continue; i++; }
else {
document.write("The number is " + i + "<br> <br>"); }
}//for ends
</SCRIPT>
</BODY>
</HTML>
Output:
As you can see every time the variable ‘i’ takes the value of 3,6 or 9, the if condition becomes true and continue
statement is executed. This forces the loop to skip the current iteration and go for the next iteration. Hence the
statement ‘i++’ after continue never get executed.
More Solved Programs
1. To terminate the execution of the while loop using the break statement when the value of a variable i becomes 3
and display a message “loop break”.
336 Touchpad Web Applications-XI

