In this program, we will learn to code the Java Program to Display Factors of a Number. Before understanding the logic and the code, let’s understand, first What are Factors of a Number and How to find factors of a Number? Then we will see How to display factors of a number in Java Programming Language.
What are Factors?
A factor is a number that divides another number evenly (without any remainder). For example, Factors of 108 are 1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, & 108.
Now, let’s see the Java Program to Display Factors of a Number.
Java Program to Display Factors of a Number
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter the number : "); int number = sc.nextInt(); System.out.println("Factors of "+number+" are :"); // Finding the Factors of the Number for(int i=1; i<=number; i++){ if(number % i == 0){ System.out.print(i+", "); } } System.out.println("."); } }
Output
Enter the number : 108
Factors of 108 are :
1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, 108, .
How Does This Program Work ?
Scanner sc = new Scanner(System.in); System.out.println("Enter the number : "); int number = sc.nextInt();
In this program, we have taken the input of the number we want to display the factors of using the Scanner
class in Java.
// Finding the Factors of the Number for(int i=1; i<=number; i++){ if(number % i == 0){ System.out.print(i+", "); } }
Then, we have created a loop from 1 to number
, inside the for loop, we check whether the number is evenly divided by i
or not using the modolo
operator “%”. So, if the number
% i is equal to 0 we display the factor “i”.
This is the Java Program to Display Factors of a Number.
Conclusion
I hope after going through this post, you understand Java Program to Display Factors of a Number.
If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.
Also Read: