Loop Control Statements in Java – For, While, Do While, Enhanched For Loop

HOME

What is Loop Control?

There is a probability that we need to execute a block of code multiple times.  Therefore, instead of writing the same piece of code multiple times, Java or any other programming language provide loop control statements. There are 3 types of loops in Java

  1. for Loop
  2. while Loop
  3. do-while loop 

1) For Loop

For loop execute a block of code a number of times . In For loop, we first intialize the variable, check condition and increment/decrement value. It consists of 4 parts:-

  1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable.
  2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false.
  3. Statement: The statement of the loop is executed each time until the second condition is false.
  4. Increment/Decrement: It increments or decrements the variable value.

Syntax

for(Variable Initialization; Boolean_Expression Test; Increment/Decrement){
   //Statements
    }
 
    for (int i = 0; i < 5; i++) {
    System.out.println(i);
    }

Example

   public class For_loop {
     public static void main(String[] args) {
       for(int i=0;i<5;i++)
    {
       System.out.println("Value of i is: "+i);
    }
   System.out.println("-----------------------------------------------------");
       for (int j=5;j>0;j--)
       {
              System.out.println("Value of j is: "+j);
        }
     }
   }
 
Output
Value of i is: 0
Value of i is: 1
Value of i is: 2
Value of i is: 3
Value of i is: 4
--------------------------------------------------------
Value of j is: 5
Value of j is: 4
Value of j is: 3
Value of j is: 2
Value of j is: 1
  •    Statement 1 sets a variable before the loop starts (int i = 0).
  •    Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
  •    Statement 3 increases a value (i++) each time the code block in the loop has been executed.

2) While Loop

 The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

Syntax

   while(Boolean_Expression Test)
    {
        //Statements
    }

Example

  public class While_Loop {
    public static void main(String[] args) {
       int i=0;
       while (i<15)
       {
            i=i+3;
            System.out.println("Value of i is :"+i);
         }
  System.out.println("--------------------------------------------"); 
  // In this case, value of j will be 0 and it will run infinite times. 
    int j=0;
    while(j<15)
    System.out.println("Value of j is :"+j);
    {
       j=j+3;
    }
  }
 }

Output
Value of i is :3
Value of i is :6
Value of i is :9
Value of i is :12
Value of i is :15
--------------------------------------------
Value of j is :0
Value of j is :0

   3) What is the difference between for and while loop?

   While loop is used in situations where we do not know how many times loop needs to be executed beforehand.
   For loop is used where we already know about the number of times loop needs to be executed. Typically for a index used in iteration.

 4)  Do While Loop

A do while loop is exactly similar to while loop and the only difference between two is that the do while loop executes the statement at least one time. As it start with do keyword and the boolean expression appears at the end of the loop.

Syntax

   do{
         //Statements
       }while(Boolean_Expression Test);

Example

public class Do_While_Loop {
       public static void main(String[] args) {  
         int i=0;
          do 
          {
             i=i+3
             System.out.println("Value of i is :"+i);
           }
           while (i<15);
           System.out.println("-------------------------------------------");
           //Condition is already satisfied, still 1 round of execution
           int j=10;
           do
          {
            j=j+2;
            System.out.println("Value of i is :"+j);
           }
       while (j<10);
       }
   } 
   
Output
Value of i is :3
Value of i is :6
Value of i is :9
Value of i is :12
Value of i is :15
-----------------------------------------------------
Value of i is :12

5) What is the difference between While Loop or do- while loop?

1) while loop first check the condition then enter the body whereas do-while first enter the body and then check the condition.
2) while is a entry controlled loop whereas do-while is an exit controlled loop.
3) In while, condition comes before the body whereas in do-while, condition comes after the body.

 6) Enhanced for loop in Java

 It is used to traverse array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.

It works on elements basis, not index. It returns element one by one in the defined variable.

Syntax

for (data_type variable: array_name)

Example

public class Enhanced_Loop {
       public static void main(String[] args) {

          // Array of String storing days of the week
           String days[] = { "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"};
           
           // Enhanced for loop, this will automatically iterate on the array list 
           for (String dayName : days) 
          {
             System.out.println("Days ==> "+ dayName);
           }
             System.out.println("");
             
             // Normal for loop
           for (int i=0; i < days.length; i++) {
               System.out.println("Days ==> "+ days[i]);
           }
       }
   }

Output
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun 
 
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s