In this tutorial you will learn about the Java Program to Find HCF of two numbers and its application with practical example.
Java Program to Find HCF of two numbers
In this tutorial, we will learn to create a Java program that will find the HCF of two numbers using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- While loop in Java programming.
- Arithmetic operations in Java Programming.
Program Description:-
In Java programming, it is possible to take numerical input from the user and find HCF of two numbers with the help of a very small amount of code. The Java programming language has many types of predefined libraries which have support for the function in them with the help of these arithmetic expressions we can find the HCF. The program first takes the two numbers in input then it will find the HCF using the for loop and the conditional statements. At last, we will print the output HCF to the user.
With the help of this program, we can find HCF.
Here,
HCF:- Highest Common Factor.
Program to find HCF of two numbers:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class HCF { public static void main(String args[]){ //Declaring the required variables for the program. int a, b, i, hcf = 0; //Taking the input from the user. Scanner sc = new Scanner(System.in); //Taking the first number form the user. System.out.println("Enter first number :: "); a = sc.nextInt(); //Taking the first number form the user. System.out.println("Enter second number :: "); b = sc.nextInt(); //Calculating the HCF of two numbers. for(i = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } //Printing the output HCF of the numebrs. System.out.println("HCF of given two numbers is ::"+hcf); } } |
Output:-
In the above program, we have first initialized the required variable.
- a = it will hold the integer value1.
- b = it will hold the integer value2.
- t = it will hold the integer temporary value.
- hcf = it will hold the integer value of calculated hcf.
Input number from the user.
Program Logic Code.
Printing output