In while loop, at the start of the loop the program checks the condition. If condition is met, statements inside the loop are executed and keeps repeating till the condition becomes false. As soon as the condition is false, the program control comes out from the loop and starts executing the statement immediately after the loop. The while loop looks like as follows -
while (condition) { statements; }
Let's use the same example we used in for loop. Instead for loop, here we are using the while loop.
Class WhileExample1 (WhileExample1.java)
public class WhileExample1 { public static void main(String args[]) { int i = 1, sum = 0; while(i <= 10) { sum = sum + i; i++; } System.out.println(sum); } }
Here the loop is executed till variable i is 10. To execute the statement in the loop, it needs to satisfy the condition always. But there is one more form of while loop - do-while loop.
do { statements; } while (condition);
In do-while loop, the statements in the loop are executed first time and at the end of the loop, the condition is checked. If the condition is met, it goes back to the loop. The statements are executed repeatedly till the condition becomes false.
Class WhileExample2 (WhileExample2.java)
public class WhileExample2 { public static void main(String args[]) { int i = 0, sum = 0; do { sum = sum + i; i++; } while(i <= 10); System.out.println(sum); } }
Notice that we are putting ; after while (condition). The statements in the loop are executed once. At the end of the loop, it checks the condition.
No comments:
Post a Comment