Loops
Loops
P R E S E N TAT I O N
THREE TYPE OF LOOP
• For loop
• While loop
• Do while loop
FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
SYNTAX
The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
Next, the condition is evaluated. If it is true, the body of the loop is executed.
After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition).
FLOW DIAGRAM
EXAMPLE
#Program:
for(int i=0;i<3;i++){
System.out.println("Using For loop: "+i);
}
#Output:
Using For loop: 0
Using For loop: 1
Using For loop: 2
WHILE LOOP
#Output:
Using While loop: 0
Using While loop: 1
Using While loop: 2
DO WHILE LOOP
• A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.
SYNTAX
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop executes again. This process repeats until the given condition becomes false.
FLOW DIAGRAM
EXAMPLE:
#Program:
int i=0;
do{
System.out.println("Using Do while loop: "+i);
i++;
}
while(i<3);
#Output:
Using Do while loop: 0
Using Do while loop: 1
Using Do while loop: 2
BREAK STATEMENT
Terminates the loop statement and transfers execution to the statement immediately
following the loop or switch.
#Output:
Output:0
Output:1
CONTINUE STATEMENTS
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
#Output:
Output:0
Output:1
Output:3
Thank You.