Page 201 - CA_Blue( J )_Class9
P. 201

12              System.out.println("Sum of numbers from 1 to 5 : "+s);
                  13          }

                  14      }

                 You will get the following output:














                                                           Dry Run & Output
                           Step Number                 i                    s=s+i          System.out.println(s);
                                1                      1                  0+1=1
                                2                      2                  1+2=3

                                3                      3                  3+3=6

                                4                      4                  6+4=10
                                5                      5                  10+5=15                   15
                 Since, the do-while loop executes at least once, we can term it as an Exit Control Loop.

                 Example of a do-while loop working as an Exit Control loop:

                                                                                                    Start


                                                                                                Initialise i = 1



                                                                                                Display "Exit
                          int i=1;
                                                                                               Control Loop"
                          do
                          {
                              System.out.println("Exit Control Loop");
                                                                                               Increment i by 1
                              i++;
                          }while(i<=0);


                                                                                      true          Is
                                                                                                  i < = 0?

                                                                                                      false
                                                                                                   Stop


                 Explanation of the above example: Value of i is 1 and condition to be checked i<=0. This means that the condition
                 will not satisfy. Since the condition is checked at last, the line System.out.println("Exit Control loop”); will execute
                 only once.




                                                                                       Iterative Constructs in Java  199
   196   197   198   199   200   201   202   203   204   205   206