Computer Applications
Predict the output :
class FindFac {
public static void main (String args[]) {
for(int i = 2; i <= 100; i++) {
System.out.print("Factors of" + i + ": ");
for(int j = 2; j < i; j++)
if((i % j) == 0)
System.out.print(j + " ");
System.out.println();
}
}
}
Answer
The output of the program is a list of the factors of each integer between 2 and 100, printed to the console.
Factors of2:
Factors of3:
Factors of4: 2
Factors of5:
Factors of6: 2 3
Factors of7:
Factors of8: 2 4
Factors of9: 3
Factors of10: 2 5
...
...
Factors of95: 5 19
Factors of96: 2 3 4 6 8 12 16 24 32 48
Factors of97:
Factors of98: 2 7 14 49
Factors of99: 3 9 11 33
Factors of100: 2 4 5 10 20 25 50
Working
This Java program finds the factors of integers between 2 and 100.
The program uses two nested for
loops to generate the integers to be factored and to find their factors. The outer for
loop generates the numbers from 2 to 100 whose factors are to be found.
The inner for
loop starts with j = 2
and continues until j < i
, incrementing j
by 1 each time through the loop. This loop checks whether j
is a factor of i
by checking whether the remainder of i
divided by j
is equal to zero. If j
is a factor of i
, it is printed to the console on the same line as the message "Factors of [i]: ".
After the inner loop has completed, a newline character is printed to the console using System.out.println()
. This causes the next message ("Factors of [i+1]: ") to be printed on a new line.
Let us consider the execution of nested 'for' loop for a single value of i (say, i = 6). The given table follows the execution:
i | i <= 100 | j | j < i | (i % j) == 0 | Output | Remarks |
---|---|---|---|---|---|---|
6 | True | 2 | True | True | Factors of 6: 2 | 6 % 2 = 0 |
3 | True | True | Factors of 6: 2 3 | 6 % 3 = 0 | ||
4 | True | False | 6 % 4 ≠ 0 | |||
5 | True | False | 6 % 5 ≠ 0 | |||
6 | False | j becomes equal to i, inner loop terminates and i becomes 7 |
Related Questions
Give the output of the following program segment and also mention how many times the loop is executed.
int i; for (i = 5 ; i > 10; i++) System.out.println(i); System.out.println(i * 4);
Find the error
for(count = 0, count < 5, count = count + 1) System.out.println("This is count:" + count); System.out.println("Done!");
Predict the output :
class Test { public static void main (String args[]) { double x, y, z ; x = 3; y = 4; z = Math.sqrt(x * x + y * y); System.out.println("z = " + z); } }
Predict the output :
class Power { public static void main(String args[]) { int e = 5, result, i; result = 1 ; i = e ; while(e > 0) { result *= 2 ; e--; } int n = result /2, p = i - 1; System.out.println("2 to the power of " + i + " is " + result); System.out.println("2 to the power of " + p + " is " + n); } }