Page 201 - ComputerScience_Class_11
P. 201

The syntax of the while loop is:

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

                  Program 5      Write a Java program to check if a number is a sum product number. A sum product number is
                                 a number for which the product of its digits multiplied by the sum of its digits is equal to the
                                 original number.
                   1      import java.util.Scanner;

                   2      public class SumProductNumber {
                   3          public static void main(String[] args) {
                   4              Scanner sc = new Scanner(System.in);
                   5              System.out.print("Enter a number: ");
                   6              int n = sc.nextInt();
                   7              int r, sum = 0, product = 1, temp;

                   8              temp = n;
                   9              while (temp > 0) {
                  10                  r = temp % 10;
                  11                  sum = sum + r;

                  12                  product = product * r;
                  13                  temp = temp / 10;
                  14              }
                  15              if ((sum * product) == n) {
                  16                  System.out.println(n + " is a sum product number");
                  17              } else {

                  18                  System.out.println(n + " is not a sum product number");
                  19              }
                  20              sc.close();
                  21          }

                  22      }

                 The output of the preceding program is as follows:
                       BlueJ: Terminal Window - Java

                   Options

                  Enter a number: 135
                  135 is a sum product number

                 Since the condition is checked before the execution of the while loop, we can call it an Entry Controlled Loop.




                                                                                              Statements and Scope  199
   196   197   198   199   200   201   202   203   204   205   206