Loops in Java

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. 

Types of loops

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:

  1. For loop
  2. While loop / Entry control loop
  3. Do while loop / Exit control loop

Let’s see the differentiation of loops in Tabular Form:

For Loop           
  • When you know exactly the number of times the loops want to execute through a set of statements, it is recommended to use.
  • If the condition is true, the For Loop statement will execute; that means a set of statements will execute repeatedly zero or more times.
  • If the looping condition is false, it stops the execution of the set of statements & control will skip to the statement followed after the loop.
While Loop
  • It can be used when you are not sure about the number of iterations. It is recommended when the number of iterations is not fixed. .
  • It performs the repetition specified in the body zero or more times, it allows code to execute repeatedly based on the condition.
  • If the condition is false, it will stop execution.
  • Also called Entry Control Loop.
Do While Loop
  • Also called Exit Control Loop, it is a control flow statement that executes at least on the part of the program and the next level execution depends upon the given condition.
  • It is similar to the while loop and the only difference is, it executes the statements at least once before it checks the Boolean condition.
  • If the condition is false, it steps execution.

Now we can look in detail at the working of each loop statement in java.

FOR LOOP 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:

  • Initialization
  • Condition/Test statement
  • Update statement/ Increment or Decrement expression

The timeline of the for-loop syntax is as follows:


for(initialization; testing_condition; increment/ decrement) 
{ 
// Block of codes 
/ statements …… 
…... 
}
 
flowchart

FlowChart of for loop in Java

The execution of the for-loop statement is as follows:

  1. 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.

  2. 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.

  3. 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


Other Features of For-Loop:

The for loop has several other capabilities.

  1. More than one variable can be initialized at a time.

    The statements n=1; for(i=0; i<=10; i++) can be written as

    
    for(n=1; i=0; i<=10; i++)
     
    
  2. The increment section also has more than one part.

    
    for(n=1; i=10; n<=i; n++,i--)
    {
      ……
      ……
    }
     
    
  3. The test conditions have any compound relation and testing need not be limited to the loop control variable.

    
    sum=0;
    for(i=1, i<10 && sum<50; i++)
    {
      ……
      ……
    }
    
     
    

Nested for Loops in Java

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:


* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 

The Enhanced for Loop

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 Type represents the data type or object used
  •  Identifier refers to the name of a variable
  •  Expression is an instance of java. lang.Iterable interface or an array

The While Loop

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:

while

 

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.

NESTED WHILE LOOP in JAVA

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

The do-while Statement in Java

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.

Program using a do-while loop:


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 Vs do-While

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