Java -Loops

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we have three types of basic loops
  • for loop
  • do-while loop
  • while loop

1.while loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Syntax:

while (boolean condition)
{
   statements...
}



Note: The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely.


Simple while loop example



public class KnfWhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i <=10) {
System.out.println(i);
i++;
}
}
}

Output:

0
1
2
3
4
5
6
7
8
9
10

2.for loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:

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. It is an optional condition.

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. It is an optional condition.

Statement: The statement of the loop is executed each time until the second condition is false.

Increment/Decrement: It increments or decrements the variable value. It is an optional condition.



Syntax:


for(initialization;condition;incr/decr){  
//statement or code to be executed  



Simple for loop example



public class KnfForLoopExample {
public static void main(String[] args) {
for (int i = 0; i <=10; i++) {
System.out.println(i);
}
}
}

Output:

0
1
2
3
4
5
6
7
8
9
10

3.do-while loop

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.

Syntax:



do{  

//code to be executed  

}while(condition);  



public class KnfDoWhileExample {  
public static void main(String[] args) {  
    int i=1;  
    do{  
        System.out.println(i);  
    i++;  
    }while(i<=10);  
}  
}  

Output:
1
2
3
4
5
6
7
8
9
10

This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments