Here in this tutorial, we are going to see how the looping statements or iteration statements are used in Java programming for running a set of instructions multiple times based on some conditions. As you know, a computer can perform repetitive operations any number of times, tirelessly for 10, 100, or even 100000 times. so, every programming language has such features to control the flow of the program in the number of times of execution.
Loops are control flow statements that provide a way to control the program’s flow into different sections by repetitively executing the same set of statements until the termination condition is met. A loop in a computer programming language helps a set of instructions/functions to be executed repeatedly up to a desired number of times until some conditions become true. The block of codes may be executed any number of times, from 0 to infinite number. If a loop continues forever, it is called an Infinite loop
Java has three types of loops for the execution of a set of instructions/functions multiple times. The basic functionality of these repetition statements loops are similar, but they differ in syntax and working time. Also, the control structure is classified based on the position of the control statements in the loop, entry-controlled loop, or exit-controlled loop.
The three types of loops in java are the following:
For Loop |
|
While Loop |
|
Do While Loop |
|
Now we can look in detail at the working of each loop statement in java.
In cases, if you know the number of times required to execute a block of code, we can use For loop. For example; if you want to check the absenteeism record of employees working in a firm, you can use a for loop as you are aware of the employee strength in the office.
For loop is a control flow statement that is used for executing a block of codes repeatedly multiple times until satisfied for a particular condition.
The For loop structure is as follows:
The timeline of the for-loop syntax is as follows:
for(initialization; testing_condition; increment/ decrement)
{
// Block of codes
/ statements ……
…...
}
The execution of the for-loop statement is as follows:
Initialization in for loop
Here, in this part, we initialize the control variable with a starting value that acts as the start of a for-loop. The initialization part of the for-loop executes only once and it is executed at the beginning of the loop before testing the condition. Also, note that it is optional to initialize or not.
Let’s see an example;
for(int i=0; i<5; i++)
{
System.out.println(i);
}
int i=0
is the initialization part, where an integer variable i
is initialized with the value 0
.
Test Condition in for loop
This particular section is to provides the testing conditions for the loop to execute. The test condition should be stated carefully to, perform the desired number of executions or determine when the loop will exit. The test condition is repeated at each iteration and terminates until the condition is met/ satisfied.
In the above example, the value of the variable is tested i.e, i <5
is the condition to be tested; means the variable i should be less than 5, otherwise, the loop is terminated and control will transfer to the statements immediately after the loop.
Update statement in for loop
Commonly known as Increment/ Decrement expression. It is usually used to update the control variable after each iteration, executed every time after the statement section has been iterated. The for loop also allows for negative increments.
i++
is the update statement in the above example. When the condition is true, then the control enters the loop for executing the statement/ block of codes, and once when the iteration is completed entirely, the value of the variable is incremented by 1, i=i+1
. And the new value of the control variable is tested against the condition.
Now let us look into an example for understanding the iteration in for-loop.
class ForLoopEx {
public static void main(String[] args) {
for( int i=0; i<=10; i++)
{
System.out.println(i*i);
}
}
}
This for loop is executed 11 times and prints the square of the digits 0 to 10 in one line.
Output:
0 1 4 9 16 25 36 49 64
The for loop has several other capabilities.
The statements n=1; for(i=0; i<=10; i++) can be written as
for(n=1; i=0; i<=10; i++)
for(n=1; i=10; n<=i; n++,i--)
{
……
……
}
sum=0;
for(i=1, i<10 && sum<50; i++)
{
……
……
}
In Java, one for-loop in another for-loop is called Nesting of Loops. Each statement should be properly stated to determine easily which statements belong to each for-loop.
for (i=1; i<10; i++)
{
……
……
for (j=1; j<=5; j++)
{
…..
…..
}
……
…..
}
…….
……
Example,
public class NestedLoopEx {
public static void main(String args[]) {
int i, j, row = 10;
for (i = 0; i & lt; row; i++) // loop 1 returns the number of rows
{
for (j = 0; j & lt; = i; j++) // loop 2 returns the number of columns
{
System.out.print( & quot;* & quot;); // prints *
}
System.out.println(); // next line
}
}
}
Output:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Also called for each loop, is used to retrieve the array of elements other than using array indexes. This feature helps to traverse the array of elements, which makes the code readable. The point to be noted in a for-each loop is that it doesn’t allow the traverse of elements in reverse order. The Enhanced for-loop allows eliminating the iterators in a for loop and retrieving the elements from the collection.
The syntax:
for (Type Identifier : Expression)
{
//statements;
}
Here,
The While Loop is also called an Entry-Controlled Loop. This is the simplest looping structure in Java that checks the condition specified for the while loop. The While loop is Java's fundamental loop statement that continually executes a block of codes while a specific test condition is true.
The While loop evaluates the condition that must return a boolean value, and if the condition is true, the while loop executes the block of codes in the while loop. This continues testing expression until the condition evaluates to false and the control of the iteration is transferred out of the loop. If the test condition is false, it will not execute and the code immediately after the loop will be executed.
The basic format to define the While loop statement in the java program is:
Initialization:
While (test condition)
{
Body of the loop
}
The While Iterative Statement is as follows:
Program using While Loop
class HelloWorld {
public static void main(String[] args) {
int i;
i=0;
while (i<=10)
{
System.out.println(i*i);
i=i+1;
}
}
}
Output:
0 1 4 9 16 25 36 49 64
Note that we have given i
an initial value 0
. In the first cycle 'while' checks whether it is lesser or equal to 10 or not. As 0<10
, the codes execute and print the square of 0 as 0
. The statement 'i=i+1'
increases the value of 'i
' from 0
to 1.
Now 'while'
checks again and finds 1<10, consequently prints the square of 1 which is 1. Similarly, 2,3,4,....till 10 is printed. But at the last statement of the last loop 'i'
becomes 11'.
So 'while' finds 11 to be neither less than nor equal to 10
and the loop terminates.
Java allows to include nested while loop means while in another while. You can include any number of while in the nested concept.
Syntax:
While()
{
While()
{
…..
…..
}
….
}
See below example to print the multiplication table using nested while loop.
class NestedWhileLoopEx {
public static void main(String[] args) {
int i=1;
while(i<2)
{
int j =1;
while(j<=10)
{
System.out.printf("%d * %d = %d \n", i, j, i * j);
j=j + 1;
}
i=i + 1;
}
}
}
Output:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 1 x 6 = 6 1 x 7 = 7 1 x 8 = 8 1 x 9 = 9 1 x 10 = 10
In the While loop, it tests the condition before the loop is executed. Therefore, the body of the loop may not be executed if the condition is not met. In some programs, it is necessary to execute the body first before the test is performed. In such cases, the do-while loop can be used. Unlike For loop and While loop, the do-while loop executes the body of the loop at least once before it tests the condition. The do-while loop guarantees to execute the loop at the very first attempt for once.
The do-while loop in the java programming language can be expressed as follows:
Initialization:
do
{
Body of the loop
}
While (test condition);
The do-while loop is a control flow statement that evaluates the body of the loop first before the test condition at the bottom is performed. As you can see from the syntax, the test condition in the while statement is tested at the end of the loop; it provides an exit-controlled loop. Therefore, the do-while loop is also called an exit-controlled loop.
If the Boolean condition is satisfied, the control of the program once again evaluates the body of the loop. This continues until the condition is true. Once when the condition becomes false, the control is transferred to the statement immediately after the while statement.
public class DoWhileEx {
public static void main(String[] args) {
int i=0;
do{
System.out.println(i*i);
i++;
}while(i<=10);
}
}
Output:
0 1 4 9 16 25 36 49
While | do-while |
---|---|
It is an entry-controlled loop | It is an exit-controlled |
It will execute only if the test condition is true | It will execute at least once even if the test condition is false |
The test condition is tested first | The body of the loop is executed first before the test condition is performed |
No semicolon at the end of the while statement | A semicolon at the end of the while statement |
Evaluates the expression at the top | Evaluates the expression at the bottom |