Page 109 - 2617_JSSPS_C-7
P. 109

In the preceding code, the while loop checks the condition (i <= 10)
                 that evaluates to true. The statements written inside the body of the
                 while loop get executed. The value of the variable i will be incremented
                 by 1 (i++). The loop checks the condition again and again until the
                 value of the variable i becomes more than 10. This variable is also
                 called a control variable. The control variable defines the duration
                 until which the loop will execute.

                 The do-while Loop

                 The do-while loop is similar to the while loop. The only difference is
                 that the do-while loop will execute the statements written inside its                    Start
                 body at least once, whether the given condition returns true or false.
                 The do-while loop executes the statements written inside its body               Body of do...while loop
                 and checks the condition. If the condition evaluates to true, the loop
                 will execute again and again until the given condition becomes false.

                 The syntax of the while loop is as follows:
                                                                                             True     Conditional
                 do                                                                                    Expression

                 {
                                                                                                             False
                   [statements]
                                                                                                          Stop
                   [increment/decrement expression]
                 }                                                                              Flowchart of do-while loop

                 while(< conditional expression >);
                  Program 10:  Write a program to print the value of i from 1 to 10 using do-while loop.

                 1   public class DoWhileLoop

                 2   {
                 3       public static void main(String args[])

                 4       {

                 5           int i = 1;
                 6           do

                 7           {
                 8              System.out.println("The value of i is: " + i);

                 9             i++;

                 10            }

                 11          while (i <= 10);
                 12      }

                 13  }





                                                                                               Java Programming    107
   104   105   106   107   108   109   110   111   112   113   114