Iteration statement creates loops. A loop repeatedly executes the same set of instructions until a termination condition is met. Iteration statements are another type of 'Control Flow' statements.
Program to demonstrate the 'while' loop |
'while' loop executes the statements in its block repetitively as long as the condition expression is true. class WhileLoop { public static void main(String args[]) { int i=1; while(i<6) //This loop will be executed repeatedly until the value of i is less than 6 { System.out.println("The value of i is "+i); i++; } } } Output of this program: The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 The value of i is 5 'while' loop executes the statements inside its block repeatedly until the value of i is less than 6 in this example. So to start with 'while(i<6) i.e. while(1<6) which is true, hence it enters into the while block and prints "The value of i is 1" and then executes i++; i.e. it increments the value of i by 1. So the value of i now is 2. The loop then gets repeated with while(i<6) i.e. while(2<6) which is true -> hence prints "The value of i is 2", while(3<6) which is true -> hence prints "The value of i is 3", while(4<6) which is true -> hence prints "The value of i is 4", while(5<6) which is true -> hence prints "The value of i is 5" and while(6<6) which is false hence wont enter into the while block as the condition is false. |
Program to demonstrate the infinite times executed while loop |
'while' block will get executed infinite times if the condition expression is always true class InfiniteWhileLoop { public static void main(String args[]) { int i=1; while(i<6) { System.out.println("The value of i is "+i); } } } Output of this program: "The value of i is 1" will be printed infinite times. In this example, we've not incremented the value of i by 1 as we did in the earlier example. As a result the value of i is always 1. Since while(i<6) i.e. while(1<6) is always true, the statement "The value of i is 1" inside the while loop will be printed infinite times. |
Program to demonstrate a never executed while loop |
'while' block wont be executed at least single time when the condition expression is false. class NeverExecutedWhileLoop { public static void main(String args[]) { int i=6; while(i<6) { System.out.println("The value of i is "+i); } } } Output of this program: [No output] - Since while(i<6) i.e. while(6<6) is false, the statements inside the while block wont be executed at least once. |
Finding the mid value of 1 and 11 using the 'while' loop |
class ExampleWhileLoop { public static void main(String args[]) { int i=1,j=11; while(++i<--j); //There are no statements in the while loop, hence we have not used the flower braces. System.out.println("The mid value of 1 and 11 is "+i); } } The output of this program: The mid value of 1 and 11 is 6 |