Java Program to Display Factors of a Number

In this program, you’ll learn to display all factors of a given number using for loop in Java.

Example: Factors of a Positive Integer

  1. public class Factors {
  2. public static void main(String[] args) {
  3. int number = 60;
  4. System.out.print("Factors of " + number + " are: ");
  5. for(int i = 1; i <= number; ++i) {
  6. if (number % i == 0) {
  7. System.out.print(i + " ");
  8. }
  9. }
  10. }
  11. }

When you run the program, the output will be:

Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

In the above program, number whose factors are to be found is stored in the variable number (60).

The for loop is iterated until i <= number is false. In each iteration, whether number is exactly divisible by i is checked (condition for i to be the factor of number) and the value of i is incremented by 1.