Session 2 |
Loops
We can repeatedly execute a sequence of code by creating a loop. Java supplies a powerful
assortment of loop constructs that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These are for
, while
and do-while
.
While loop
While loop repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Syntax:
while (expression) { //statement(s) }
The while statement evaluates expression which return a boolean value. If the expression is true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
Example:
public class Counter { public static void main(String[] args){ int count = 1; while (count < 4) { System.out.println("Count is: " + count); count++; } } }
The output of the program would be:
Count is: 1 Count is: 2 Count is: 3
Do ... while loop
Do... While loop is like a while statement, except that it tests the condition at the end of the loop body.
Syntax:
do { //statement(s) } while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.
Example:
public class Counter { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 4); } }
The result is the same as in the previous example.
For loop
For loop provides a compact way to iterate over a range of values.
Syntax:
for (initialization; termination; increment) { //statement(s) }
Keep in mind, that
- the initialization expression initializes the loop; it is executed once as the loop begins;
- when the termination expression evaluates to false, the loop terminates;
- the increment expression is invoked after each iteration through the loop.
Example:
public class Counter { public static void main(String[] args){ for(int i=1; i<4; i++){ System.out.println("Count is: " + i); } } }
The result is the same as in the previous example.
Like in Python, use:
- continue to break the current iteration and proceed with the next iteration;
- break to jump out of the loop.
Some more examples on loops:
Nested loops
Session 2 |