COMPUTER PROGRAMMING 1
Loops in Java
CC 102 - Module 6
GEMMARIE T. MUÑOZ
Loops in Java
01
02
03
Loops
Loops can execute a block of code as
long as a specified condition
is reached.
Condition: The condition must be a
Boolean expression
(evaluates to True or False).
WHILE Loop
It is used when you want a Code Block to
run repeatedly WHILE a CONDITION is met
WHILE Loop
Syntax:
while(condition){
//Do everything you want here
}
WHILE Loop
How it works?
✓ Condition Check: The loop first checks the condition.
✓ Execution: If the condition is true, the code block inside
the loop is executed.
✓ Repeat: The condition is checked again, and the process
repeats as long as the condition remains true.
✓ Termination: When the condition becomes false, the loop
terminates, and the program continues with the
next statement after the loop.
WHILE Loop
Syntax:
int i = 0;
while(i < 5){
System.out.println(i);
i++;
}
DO-WHILE Loop
Same as the WHILE Loop but it EXECUTES
the Code Block before checking the
CONDITION.
DO-WHILE Loop
Syntax:
do{
//Do everything you want here
} while(condition);
DO-WHILE Loop
How it works?
✓ Do: The code block inside the loop is
executed at least once, regardless
of the condition.
✓ While: After the code block executes,
the condition is checked. If the
condition is true, the code block
runs again. If the condition is false,
the loop terminates.
DO-WHILE Loop
Syntax:
int i = 0;
do{
System.out.println(i);
i++;
} while(i < 5);
FOR Loop
It is used when you want a Code Block to
run repeatedly WHILE the Condition is Met
It’s a more compact format but more
complicated version of a While Loop.
For Loops are commonly used to iterate
through Collections like Arrays.
FOR Loop
Syntax:
for(initialization; condition; updation){
//Do everything you want here
}
FOR Loop
How it works?
✓ Initialization: This part executes only once at the beginning of
the loop. It usually initializes a counter variable.
✓ Condition: This expression is evaluated before each iteration.
If the condition is true, the loop body executes.
If it's false, the loop terminates.
✓ Increment/Decrement: This part is executed after each
iteration. It usually updates the counter variable.
FOR Loop
Syntax:
for(int i = 0; i < 5; i++){
System.out.println(i);
}
Thank you!