Page 190 - Computer science 868 Class 12
P. 190

7.3.3 do while loop
              In Java ‘do-while’ loop, the body of the loop is executed before checking the test condition. Hence, it is called an
              exit-controlled loop as the condition lies at the end. The control enters the loop without checking for the first time.
              This loop will execute at least once even if the condition is false. It is used when the number of iterations is not known
              or fixed.
              The syntax of the do-while loop is:
                  initialisation;
                  do
                  {
                  // job performed by the body of the loop
                  increment or decrement;
                  } while(condition for testing);

              For example,
              1.  Print the factorial of a number.

                  class factorial
                  {
                      public static void main(int n)
                      {
                          int i, f=1;
                          i=1;
                          do
                          {
                               f = f*i;
                               i = i+1;
                          }while(i<=n);
                          System.out.println("Factorial of " + n + " is : " +f);
                      }
                  }
              2.  Print whether a number is an Armstrong number or not.

                  int n=153, r, temp, s=0;
                  temp=n;
                  do
                  {
                      r = temp%10;
                      s = s+(r*r*r);
                      temp = temp/10;
                  }
                  while(temp>0);
                  if(n == temp)
                      System.out.println(n+ " is an Armstrong number");
                  else
                      System.out.println(n+ " is not an Armstrong number");
              Different categories of loops:
              •  Delay Loop
              •  Null Loop/Body less Loop/Empty Loop
              •  Infinite Loop/Endless Loop
              •  Finite Loop
              •  Nested Loop
              •  Fixed Iteration Loop
              •  Unfixed Iteration Loop



                188188  Touchpad Computer Science-XII
   185   186   187   188   189   190   191   192   193   194   195