Page 180 - Cs_withBlue_J_C11_Flipbook
P. 180

The for Loop
              The Java for loop executes a set of statements repeatedly for a fixed number of times.

              As soon as the control statement does not match the condition, the loop terminates.
              The syntax of for loop is:

                  for (initialisation; test condition; increment or decrement)
                  {
                      // body of the loop
                  }
              For example:
              To check whether the given number (n) is a perfect number or not.

                  int s=0;
                  for (int i=1; i<=n/2; i=i+1)
                  {
                  if(n%i==0)
                  {
                      s=s+i;
                  }
                  }
                  if(s==n)
                      System.out.println(n+ " is a perfect number");
                  else
                      System.out.println(n+ " is not a perfect number");
              The above example  finds all the factors of the number “n” and adds it in a variable “s”. The loop will continue till half
              of the number. If the variable “s” is equal to “n”, then it is a perfect number.
              Since the condition is checked before the execution of the for loop, we can call it an “Entry Controlled Loop”.

              The while Loop
              The Java while loop is used to execute a set of statements repeatedly based on a given condition. It is used when the
              number of iterations is not known.
              The syntax of the while loop is:

                  Initialisation;
                  while(test condition)
                  {
                  // body of the loop
                  increment or decrement;
                  }
              For example:

              To check whether the given number is a sum product number or not  (A natural number that is equal to the product of
              the sum of its digits and the product of its digits is a sum product number.)
                  int n=123, r, s=0, p=1, temp;
                  temp=n;
                  while(temp>0)
                  {
                      r=temp%10;
                      s=s+r;
                      p=p*r;


                178178  Touchpad Computer Science-XI
   175   176   177   178   179   180   181   182   183   184   185