;

Java Program to Display Factors of a Number


Tutorialsrack 10/07/2021 Java

In this Java program, you’ll learn how to display factors of a positive or negative number. In this program, we used the following java basics such as for loop, and if..else condition.

Here is the code of the program to display factors of a positive or negative number:

Example 1: Java Program to Display Factors of a Positive Number

Program - Java Program to Display Factors of a Positive Number
//Java Program to Display Factors of a Positive Number
 
import java.util.Scanner;
 
public class JavaPrograms {
 
	public static void main(String[] args) {
 
		Scanner sc = new Scanner(System.in);
 
		System.out.println("Enter a Number: ");
		int number = sc.nextInt();
 
		System.out.print("Factors of " + number + " are: ");
 
		// loop runs from 1 to 60
		for (int i = 1; i <= number; ++i) {
 
			// if number is divided by i
			// i is the factor
			if (number % i == 0) {
				System.out.print(i + " ");
			}
		}
	}
}
Output

Enter a Number: 

20

Factors of 20 are: 1 2 4 5 10 20 

Example 2: Java Program to Display Factors of a Negative Number

Program - Java Program to Display Factors of a Negative Number
//Java Program to Display Factors of a Negative Number
 
import java.util.Scanner;
 
public class JavaPrograms {
 
	public static void main(String[] args) {
 
		Scanner sc = new Scanner(System.in);
 
		System.out.println("Enter a Number: ");
		int number = sc.nextInt();
 
		System.out.print("Factors of " + number + " are: ");
 
		// run loop from -60 to 60
		for (int i = number; i <= Math.abs(number); ++i) {
 
			// skips the iteration for i = 0
			if (i == 0) {
				continue;
			} else {
				if (number % i == 0) {
					System.out.print(i + " ");
				}
			}
		}
	}
}
Output

Enter a Number: 

-20

Factors of -20 are: -20 -10 -5 -4 -2 -1 1 2 4 5 10 20


Related Posts



Comments

Recent Posts
Tags