Below is the list of commonly used loops –
for loop
- A for loop is used when number of iteration is fixed i.e., how many times you want to loop through a block of code.
- Syntax:
for (initialization condition; testing condition; increment / decrement) {
//block of code
}
- Example:
for (int i=1; i<=5; i++) {
System.out.println(i);
}
enhanced for loop
- An enhanced for loop is used to iterate through the elements of a collection or array in sequential manner.
- Syntax:
for (Datatype element : Collection / array) {
//block of code
}
- Example:
for(String s: names) {
System.out.println(s);
}
while loop
- A while loop is like a repetitive if condition, that loops through a block of code as long as the specified condition is true. It is known as entry controlled loop.
- Syntax:
while(condition) {
//block of code
}
- Example:
int i=1;
while(i>5) {
System.out.println(i);
i++;
}
do while loop
- A do while loop is similar to while loop. The only difference is that it checks for condition after executing the block of code. It is executed at least once. It is known as exit controlled loop.
- Syntax:
do {
// block of code
} while (condition);
- Example:
int i=1;
do {
System.out.println(i);
i++;
}while(i>5);