Q:

Java program to calculate HCF of two numbers

belongs to collection: Java Basic Programs

0

Java program to calculate HCF of two numbers

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will read two integer numbers and find the Highest Common Factor (HCF) for both numbers.

Program/Source Code:

The source code to calculate the HCF of two numbers is given below. The given program is compiled and executed successfully.

// Java program to calculate the 
// HCF of two numbers

import java.util.Scanner;

public class Main {
  static int CalHcf(int num1, int num2) {
    int temp = 0;

    if (num1 == 0 || num2 == 0)
      return 0;

    while (num2 != 0) {
      temp = num1 % num2;
      num1 = num2;
      num2 = temp;
    }
    return num1;
  }

  public static void main(String[] args) {
    int num1 = 0;
    int num2 = 0;
    int hcf = 0;

    Scanner myObj = new Scanner(System.in);

    System.out.printf("Enter first number: ");
    num1 = myObj.nextInt();

    System.out.printf("Enter second number: ");
    num2 = myObj.nextInt();

    hcf = CalHcf(num1, num2);
    System.out.printf("HCF of %d,%d is: %d\n", num1, num2, hcf);
  }
}

Output:

Enter first number: 40
Enter second number: 100
HCF of 40,100 is: 20

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, we created a public class Main. It contains two static methods CalHcf() and main().

The CalHcf() method is used to calculate the HCF of given numbers and return the result to the calling method.

The main() method is an entry point for the program. And, we read two integer numbers from the user using the nextInt() method. Then we called CalHcf() method to calculate HCF and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to multiply two numbers using plus (+... >>
<< Java - Calculate LCM (Least Common Multiple) using...