Friday, 27 January 2017

WHILE LOOP IN JAVA

It is a universal conditional controlled statement. Since it can be supported by all the existing programming tools. While loop executes statements based on certain conditions. But unlike ‘for’ loop, ‘while’ loop doesn’t have variable initialization or increment/decrement. Syntax –

while(test expression){
Statements to be executed
}

In the beginning of while loop, test expression is checked. If it is true, codes inside the body of while loop inside the parenthesis are executed and again the test expression is checked and process continues until the test expression becomes false.

Example –
public class Loop1 {
          public static void main(String[] args) {
                   int a=1;
                   while(a<11)
                   {
                             System.out.print(a+" ");
                             a++;
                   }
          }
}

Output –
1 2 3 4 5 6 7 8 9 10

Explanation –

1. Variable a of type int is declared and initialized with value of 1. int a=1;
2. A while loop is started with condition a<11. a is initialized as 1 so 1<11 is true and hence the value of a is printed as 1 using print().
3. Then a is incremented inside while loop a++; so a becomes 2.
4. while loop again checks for condition a<11, a is 2 so 2<11 is true and once again the value of a is printed.
5. The cycle continues until a is 10. When a becomes 11 condition fails. a<11
6. Hence control jumps out of while loop.

No comments:

Post a Comment