Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 6(ii)

6 marks

Computer ScienceISC 2022 Computer Science - Specimen paper (Semester 2), Paper 1ProgramRecursion

Write the program described below.

A class Gcd has been defined to find the Greatest Common Divisor of two integer numbers. Some of…

A class Gcd has been defined to find the Greatest Common Divisor of two integer numbers. Some of the members of the class are given below: Class name: Gcd Data member/instance variable: num1: integer to store the first number num2: integer to store the second number Member functions/methods: Gcd(): default constructor void accept(): to accept the numbers int gcd(int x, int y): return the GCD of the two numbers x and y using recursive technique void display(): displays the result with an appropriate message Specify the class Gcd, giving details of the Constructor, void accept(), int gcd(int, int), and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Open in the Recursion visualiserRead the note: ISC Practicals and Theory - GCD

Answer

Answer

import java.util.*;
class Gcd
{
    int num1, num2;

    Gcd()
    {
        num1 = 0;
        num2 = 0;
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first number: ");
        num1 = sc.nextInt();
        System.out.print("Enter second number: ");
        num2 = sc.nextInt();
    }

    int gcd(int x, int y)
    {
        if (y == 0)
            return x;
        return gcd(y, x % y);
    }

    void display()
    {
        System.out.println("GCD of " + num1 + " and " + num2 + " = " + gcd(num1, num2));
    }

    public static void main(String[] args)
    {
        Gcd ob = new Gcd();
        ob.accept();
        ob.display();
    }
}
The recursive method uses Euclid's algorithm: gcd(x, y) = gcd(y, x % y) until y becomes 0. Sample run: 48 and 18 gives 6.