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