Loop in java

Loop in Java is known as a repetition, it  allows the programmer to point out that an action is to be repeated while some condition remain true.

It is implemented in one of three ways:-

1. While loop 

2. do/while loop

3. for loop

while loop 

 The while loop architecture is sufficient to provide any form of repetition. In the while loop, the loop-continuity is tested at the beginning of the loop before the body of the loop is performed. All the things that can be done with the do/while loop and the for loop can be done with the while loop.

Syntax

while(condition)
{
   statement(s);
}

 

Example

public class WhileLoop {
    public static void main(String args[]){
         int array[]={5,16,95,99,100,180,300};
         //array index starts with 0 
         int x=0;
         while(x<7){
              System.out.println(array[x]);
              x++;
         }
    }
}

Output
5
16
95
99
100
180
300

 

do/while loop

The do/while loop tests the loop-continuity condition after the loop body is executed; therefore, the loop body is always executed at least once . When the do/while stop, executing the continues with the statement after the while clause. 

Note :- It is not essential  to use braces in the do/while loop if there is only one statement in the body .However, the bracket is usually contained to avoid confusion between the while and do/while loop.

Syntax

do
{
   statement(s);
} while(condition);

Example

public class DoWhileLoop {
    public static void main(String args[]){
         int array[]={5,16,95,99,100,180,300};
         //array index starts with 0
         int i=0;
         do{
              System.out.println(array[i]);
              i++;
         }while(i<7);
    }
}

 Output
5
16
95
99
100
180
300

 

for loop 

The for repetition architecture handles all the details of opposite-controlled repetition.In the for loop the increment expression is executed ,then the loop continuation test is evaluated.

Syntax

for(initialization; condition ; increment/decrement)
{
   statement(s);
}

In this initialization is used to initialize (boot up) the loop's control variable, condition is used for the loop -continuation and increment/decrement is used to control variable.

Example

public class ForLoop {
    public static void main(String args[]){
         for(int x=20; x>10; x--){
              System.out.println("The number is: "+x);
         }
    }
}

Output
The number is: 20
The number is: 19
The number is: 18
The number is: 17
The number is: 16
The number is: 15
The number is: 14
The number is: 13
The number is: 12
The number is: 11

Keywords: