Professional Documents
Culture Documents
Looping and Branching (Day-4)
Looping and Branching (Day-4)
Looping and Branching (Day-4)
Technology
The keyword break ends execution of the current for, foreach, while, do
while or switch structure.
When the keyword break executed inside a loop the control automatically
passes to the first statement outside the loop.
Syntax:
break;
The Break Statement
Example:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
The Continue Statement
Sometimes a situation arises where we want to take the control to the
beginning of the loop (for example for, while, do while etc.)
skipping the rest statements inside the loop which have not yet been
executed.
Syntax:
continue;
The Continue Statement
Example:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Nested Loop
A loop can be nested inside of another loop.
Syntax:
statement(s);
// you can put more statements.
}
Nested Loop
Example:
$a=1;
while($a<=3) {
for($b=1;$b<=3;$b++) {
echo “a = $a , b = $b”;
echo “<br>”;
}
echo “<br>”;
$a++;
}
Nested Loop
Output: The above code will produce the following result:
a=1,b=1
a=1,b=2
a=1,b=3
a=2,b=1
a=2,b=2
a=2,b=3
a=3,b=1
a=3,b=2
a=3,b=3
Levels in break and continue
We can define the levels for break and continue within the nested loop
break; break the inner most loop (exit from the loop)
break 2; break the 2 nesting level loops (exit from the 2 nested
loops)
Example:
<?php
for($i = 0; $i < 10; ++$i) {
for($j = 0; $j < 10; ++$j) {
break 2;
}
echo $i;
}
echo ”i value is: ”.$i.” and j value is: ”.$j;
Output:
i value is: 0 and j value is: 0
Assignments
1) GENERATE ALL TRIANGULAR SHAPES
*
**
***
****
*****
B) ALPHABETICAL TRIANGULAR SHAPE
A
AB
ABC
ABCD
ABCDE
*
***
*****
*******
*********
***********
3) Prime Number Series. Numbers that are self divisible are Prime Numbers.
2 3 5 7 11 13
Assignments
4) Print a triangular multiplication table for 0 through 5.
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
*
***
*****
***
*