Friday, 27 January 2017

DO-WHILE LOOP IN JAVA

do while performs operation exactly like while, except for one condition. On the first cycle, condition is not checked as the condition is placed to execute the statements at least once. Syntax –

do
{
          Some code’s ;
}
while(test expression) ;

At first, codes inside body of do is executed. Then, the test expression is checked, if it is true, code/s inside body of do are executed again and the process continues until test expression becomes false (zero)

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

Output –
1 2 3 4

Explanation –
1. Variable a of type int is declared and initialized as 1.
2. Now do while loop is used to print a.
3. On the 1st cycle no condition is checked and the value of a is printed.
4. The loop continues until a is 4. When a becomes 5 the conditions (a<5) i.e. (5<5) is false so the control jumps out of do while loop.



No comments:

Post a Comment