Wednesday 5 February 2014

Control flow statements : looping : while, do-while

while
while statement executes a block of statements until a particular condition is true

Syntax
    while (expression) {
      //statements
}

The expression in the while statement must evaluates to a boolean value, other wise compiler will throw error. While statement first evaluates the expression, until the expression evaluates to true, it  executes the code inside the while block, other wise it comes out of the while loop.

Example : Print numbers from 0 to 9 using while loop.
class WhileEx{
 public static void main(String args[]){
  int var1 = 0;
  while(var1 < 10){
   System.out.println(var1);
   var1++;
  }
 }
}


Output
0
1
2
3
4
5
6
7
8
9

do-while
   do-while is also a loop construct like while, but evaluates its expression at the bottom of the loop instead of the top.

    Syntax
    do {
        //statement(s)
    } while (expression);

Example
class DoWhileEx{
 public static void main(String args[]){
  int var1 = 0;
  do{
   System.out.println(var1);
   var1++;
  }while(var1<10);
 }
}
    
Output   
0
1
2
3
4
5
6
7
8
9

Some points to Remember
1. What is the difference between while and do-while ?
 Statements within the do block are always execute at least once even if the expression evaluates to false.

Example
class CompareLoop{
 public static void main(String args[]){
  boolean flag = false;
  
  while(flag)
   System.out.println("I am in while loop");
  do
   System.out.println("I am in do-while loop");
  while(flag);
 }
}
 
Output
I am in do-while loop
         
Observation
Note that do-while executed, even if the expression “flag” is false. And if you have only one statement, then no need to put the line in between blocks{ }

Control flow statements                                                 loops                                                 Home

No comments:

Post a Comment