Coding Practice

Write a Java program to find all factors of a number

Find all factors of a number
Sample Output
Find all factors of a number.

Enter a number: 12
Factors are: 1 2 3 4 6 12
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int i, number = 100;

        Scanner input = new Scanner(System.in);

        System.out.println("Find all factors of a number.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        System.out.print("Factors are: ");
        for (i = 1; i <= number; i++) {
            
            if ((number % i) == 0) {
                
                System.out.print(i + " ");
            }
        }
    }
}
Sample Output
Find all factors of a number.

Enter a number: 20
Factors are: 1 2 4 5 10 20

No comments:

Post a Comment

Change Theme
X