do…while Loop & Loop Control Statement

  • A do..while loop is similar to¬† while loop , except that a do..while loop is guaranteed to execute at least one time.
  • A do…while loop is an exit-controlled loop.
syntax: 
Initialization; 
do{ 
     Body of the loop 
}while(test condition); 
Example: 
int x = 1; 
do{ 
      System.out.println(x); 
      x++; 
}while(x < 5); 
Output: 1 2 3 4

Loop Control Statements:-

  • The break & continue statement change the loop’s execution flow.
  • The break Statement terminates the loop and transfer execution to the statement immediately following the loop.
Example:
int x = 1;
while( x > 0 ){
    System.out.println(x);
    if( x == 4 ){
      break;
    }
    x++;
}
Output:
1 2 3 4
  • The continue statement causes the loop to skip the remainder of its body and then immediately retest its condition prior to reiterating.
  • In the words , it makes the loop skip to its next iteration.
Example:
for ( int x = 10 ; x <= 40 ; x=x+10){
         if( x == 30 ){
            continue;
         }
         System.out.println(x);
}
Output:
10  20  30