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();
        }
    }
}

Java

Java Nested for Loops

4 Likes

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:

ii <= 100jj < i(i % j) == 0OutputRemarks
6True2TrueTrueFactors of 6: 26 % 2 = 0
  3TrueTrueFactors of 6: 2 36 % 3 = 0
  4TrueFalse 6 % 4 ≠ 0
  5TrueFalse 6 % 5 ≠ 0
  6False  j becomes equal to i, inner loop terminates and i becomes 7

Answered By

1 Like


Related Questions