English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use the for loop in Java to display all factors of a given number.
public class Factors { public static void main(String[] args) { int number = 60; System.out.print("" + number + " "'s factors are: "); for (int i = 1; i <= number; ++i) { if (number % i == 0) { System.out.print(i + " "); } } } }
When running the program, the output is:
60's factors are: 1 2 3 4 5 6 10 12 15 20 30 60
In the above program, the number to be found is stored in the variable number (6in (0) .
Iterate with the for loop until i <= number is false. In each iteration, it will check if the number is completely divisible by i (i is a condition of the number's factor), and the value of i will increase1.