Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.
- for loop
- while loop
- do-while loop
Let's understand the loop statements one by one.
Java for loop
In java, for loop is similar to C and C ++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. The syntax to use the for loop is given below.
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.
Consider the following example to understand the functioning of the for-each loop in java.
Output:
Printing the content of the array names: Java C C++ Python JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
The flow chart for the while loop is given in the following image.
Consider the following example.
Output:
Printing the list of first 10 even numbers 0 2 4 6 8 10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements. However, it is recommended to use the do-while loop if we don't know the condition in advance, and we need the loop to execute at least once.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in java.
Output:
Printing the list of first 10 even numbers 0 2 4 6 8 10