WAP to display all factors of n using while loop in java.
Answers
Answer:
WAP ARE AN ENGINE MODELS BY CLW CHITRANJAN LOCOMOTIVE WORKS....
Answer:
Factors of a Positive Integer
public class Main {
public static void main(String[] args) {
// positive number
int number = 60;
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
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
Programiz
Search Programiz
Java Program to Display Factors of a Number
Java Program to Display Factors of a Number
In this program, you'll learn to display all factors of a given number using for loop in Java.
To understand this example, you should have the knowledge of the following Java programming topics:
Java for Loop
Java if...else Statement
Example 1: Factors of a Positive Integer
public class Main {
public static void main(String[] args) {
// positive number
int number = 60;
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
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
Factors of Negative Number
class Main {
public static void main(String[] args) {
// negative number
int number = -60;
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
Factors of -60 are: -60 -30 -20 -15 -12