While writing a program, there may be a situation when you need to repeat a block of code again and again up to certain number of times or up to infinity. In such situation, you would need to write loop statements.
In Java, there are 3 types of loops available:
For loop is useful when we know the starting value and ending value or the number of iterations. For loop is divided into 3 parts i.e. initialization, condition, and increment/decrement.
Example 1: WAP to print counting 1 to 10 using For Loop.
public class ForLoop { public static void main(String[] args) { int i; //for(initialization; condition; increment/decrement) for(i=1;i<=10;i++) System.out.print("For loop " + i); } }
In While loop, initialization statement appears before the while loop begins, condition appears to test the loop, increment/decrement statement will appear inside the while loop to change the variable value for the next iteration. It is better if number of iteration is not known by the user.
Example 2: WAP to print counting 1 to 10 using While Loop.
public class WhileLoop { public static void main(String[] args) { int i=1; //initialization while(i<=10) //condition { System.out.print("While Loop " + i); i++; //increment } } }
Do while loop is similar to while loop, only the different is that the condition appears in the end. So, the code is executed at least once, even if the condition is false.
Example 3: WAP to print counting 1 to 10 using Do While Loop.
public class WhileLoop { public static void main(String[] args) { int i=1; //initialization do { System.out.print("Do while loop "+i); i++; //increment }while(i<=10); //condition }