Page 393 - Cs_withBlue_J_C11_Flipbook
P. 393

Program 5      Define a class HCF which calculates the highest common factor of two numbers. The class
                                 description is as follows:
                                 Class name            :   HCF
                                 Data Members
                                 int a, b              :   To store two numbers
                                 Member Methods
                                 void accept()         :   Accepts two numbers in variables a and b respectively
                                 int calHCF(int x, int y)   :   Using recursive technique, calculates and returns hcf of x and y
                                 void print()          :   Calls calhcf(int, int) and prints the result
                                 static void main()    :     Creates  object and  calls  the other methods  to perform  the
                                                          above operation


                   1      import java.util.*;
                   2      class HCF

                   3      {
                   4          int a, b;

                   5          void accept()
                   6          {

                   7              Scanner sc = new Scanner(System.in);
                   8              // Inputting numbers

                   9              System.out.println("Enter two numbers");
                  10              a = sc.nextInt();

                  11              b = sc.nextInt();
                  12          }

                  13          int calHCF(int x, int y)
                  14          {

                  15              // Base case
                  16              if(y == 0)

                  17                  return x;
                  18              else

                  19                  return calHCF(y, x%y); // recursive case
                  20          }
                  21          void print()

                  22          {

                  23              // calling recursive method









                                                                                                                       391
                                                                                                           Recursion   391
   388   389   390   391   392   393   394   395   396   397   398