KnowledgeBoat Logo

Computer Applications

Write a program by using a class with the following specifications:

Class name — Hcflcm

Data members/instance variables:

  1. int a
  2. int b

Member functions:

  1. Hcflcm(int x, int y) — constructor to initialize a=x and b=y.
  2. void calculate( ) — to find and print hcf and lcm of both the numbers.

Java

Java Constructors

113 Likes

Answer

import java.util.Scanner;

public class Hcflcm
{
    private int a;
    private int b;
    
    public Hcflcm(int x, int y) {
        a = x;
        b = y;
    }
    
    public void calculate() {
        int x = a, y = b;
        while (y != 0) {
            int t = y;
            y = x % y;
            x = t;
        }
        
        int hcf = x;
        int lcm = (a * b) / hcf;
        
        System.out.println("HCF = " + hcf);
        System.out.println("LCM = " + lcm);
    }
    
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int x = in.nextInt();
        System.out.print("Enter second number: ");
        int y = in.nextInt();
        
        Hcflcm obj = new Hcflcm(x,y);
        obj.calculate();
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program by using a class with the following specifications: Class name — Hcflcm Data members/instance variables: (a) int a (b) int b Member functions: (c) Hcflcm(int x, int y) — constructor to initialize a=x and b=y. (d) void calculate( ) — to find and print hcf and lcm of both the numbers.

Answered By

53 Likes


Related Questions