Dremendo Tag Line

Input number and print factors using for loop in Java

for Loop - Question 9

In this question, we will see how to input a number and print its factors in Java programming using for loop. To know more about for loop click on the for loop lesson.

Q9) Write a program in Java to input a number and print its factors using for loop.

Program

import java.util.Scanner;

public class Q9
{
    public static void main(String args[])
    {
        int i,n;
        Scanner sc=new Scanner(System.in);

        System.out.print("Enter a number ");
        n=sc.nextInt();
        System.out.println("Factors are");
        for(i=1; i<=n; i=i+1)
        {
            if(n%i==0)
            {
                System.out.println(i);
            }
        }
    }
}

Output

Enter a number 12
Factors are
1
2
3
4
6
12
video-poster