Computer Science, asked by vishaloraon826, 5 months ago

write a program in java to enter a number and display all factors of the entered number. sample
input: 18 sample output 1,2,3,6,9,18​

Answers

Answered by anindyaadhikari13
3

Answer:

This is the required Java program for the question.

import java.util.*;

public class Factors    {

   public static void main(String args[])  {

       int n,i;

       Scanner sc=new Scanner(System.in);

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

       n=sc.nextInt();

       System.out.print("Factors of "+n+" are:");

       for(i=1;i<=n;i++)   {

           if(n%i==0)  {

               System.out.print(i);

               if(i!=n)

                   System.out.print(",");

           }

       }

       sc.close();

   }

}

Explanation:

  • This is a very simple program. Iterate a loop in the range 1 till n (number). Now, using % (modulus) operator, check if the number is divisible by the loop variable. If divisible, display the value of the loop variable.

Refer to the attachment for output.

Attachments:
Similar questions