×

Java Programs

Java Practice

Java program to calculate HCF of two numbers

Given two numbers, we have to write a Java program to calculate HCF of the given numbers.
Submitted by Nidhi, on February 23, 2022

Problem statement

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

Java program to calculate HCF of two numbers

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.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.