Loop is used to execute the block of code several times according to the condition given in the loop. It means it execute same code multiple times so it saves code and also helps to traverse the elements of array.
 There are 3 types of loop:

  • while loop
  • do – while loop
  • for loop

 
while Loop 
While loop execute the code until condition is false.
Syntax

while(condition){
//code
}

while loop
e.g.

public class Intellipaat {
public static void main(String args[]) {
int i = 20;
while( i <=20 ) {
System.out.println("value of i : " + i );
i++;
}
}
}

Output
value of i: 20

Learn Java

do – while loop
It also executes the code until the condition is false. In this at least once, code is executed whether condition is true or false, but this is not the case with while. While loop is executed only when the condition is true.
Syntax

do
{
//code
}while(condition);

e.g.

public class Intellipaat {
public static void main(String args[]){
int i = 20;
do{
System.out.println("value of i : " + i );
i++;
}while( i < =20 );
}
}

Output:
value of i: 20
value of i: 21
 
for loop
It also executes the code until condition is false. It is used when number of iterations are known where while is used when number of iterations are not known.
Syntax

for(initialization; Boolean_expression; increment/decrement)
{
//code
}

e.g

public class Intellipaat {
public static void main(String args[]) {
for(int i = 20; i < 25; i++) {
System.out.println("value of i : " + i);
}
}
}

Output
value of i: 20
value of i: 21
value of i: 22
value of i: 23
value of i: 24
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Recommended Videos

Course Schedule

Name Date
Python Course 2020-12-05 2020-12-06
(Sat-Sun) Weekend batch
View Details
Python Course 2020-12-12 2020-12-13
(Sat-Sun) Weekend batch
View Details
Python Course 2020-12-19 2020-12-20
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *