Page 200 - ComputerScience_Class_11
P. 200

For example:

                Program 4     Write a Java program to check if a number is a perfect number. A perfect number is a positive
                              integer that is equal to the sum of its proper divisors (excluding the number itself).

                1       import java.util.Scanner;
                2       public class PerfectNumberCheck {

                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 s = 0;

                8               for (int i = 1; i <= n / 2; i++) {
                9                   if (n % i == 0) {

                10                      s += i;
                11                  }

                12              }

                13              if (s == n) {
                14                  System.out.println(n + " is a perfect number");

                15              } else {
                16                  System.out.println(n + " is not a perfect number");

                17              }
                18              sc.close();

                19          }

                20      }

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

                 Options

                Enter a number: 6
                6 is a perfect number

              The program checks if a given number is a perfect number by calculating the sum of its proper divisors (excluding the
              number itself). It loops through numbers from 1 to n/2 to find divisors, sums them up and compares the sum with the
              original number to determine perfection.
              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.



                  198  Touchpad Computer Science (Ver. 3.0)-XI
   195   196   197   198   199   200   201   202   203   204   205