Exercise:
Write a Java Program to display factors of a number.
1.Factors of Positive Integer
Click Here to View the Solution!
public
class FactorPositive {
public static void main(String[] args) {
// Positive Integer
int number =
50;
System.out.print(
"Factors of " + number +
" are: ");
// loop runs from 1 to 50
for (
int i =
1; i <= number; ++i) {
// checks for if number is divided by value of i
// i is the factor considered the factor then
if (number % i ==
0) {
System.out.print(i +
" ");
}
}
}
}
Click Here to View the Output!
Factors of 50 are = 1 2 5 10 25 50
Click Here to View the Explanation!
- This program is used for displaying all the factors of a positive number by using a
for loop
. - Firstly, an integer variable number is initialized as
number = 50
. This is the number of which the factors are to be found. - A for loop is used that holds an initialization (
i = 1)
, a condition expression (i <= number
) and an expression for updating the value of i (++i
). The condition states that the loop will keep on iterating untili <= number
becomes false. - In every iteration, the number is checked whether it is divisible by the value of i (zero remainder). This is the condition to find if ‘i’ is a factor of the number.
- After the iteration, the value of ‘i’ is incremented by 1.
- In the end, all the factors of the number are displayed.
2.Factors of Negetive Integer
Click Here to View the Solution!
class FactorsNegetive {
public static void main(String[] args) {
// negative number
int number = -
40;
System.out.print(
"Factors of " + number +
" are: ");
// runs loop for values of -40 to 40
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 +
" ");
}
}
}
}
}
Click Here to View the Output!
Factors of -40 are: -40 -20 -10 -8 -5 -4 -2 -1 1 2 4 5 8 10 20 40
Click Here to View the Explanation!
- This program is used for displaying all the factors of a negative number by using a
for loop
. - Firstly, an integer variable number is initialized as
number = -40.
This is the number of which the factors are to be found. - A for loop is used that holds an initialization (
i = 1
), a condition expression (i <= Math.abs(number)
) and an expression for updating the value of i (++i
). The condition states that the loop will keep on iterating untili <= number
becomes false. - The
Math.abs()
function is used for the negative number -40 so that an absolute value is returned. - The loop will keep on iterating from -40 to 40. The value of i will keep on incrementing by 1 and when it will turn 0, the iteration will be skipped, and the remaining code will execute.
- The factors of the number -40 are calculated and printed on the screen.