MCQ Practice Single Best Answer Topic: ICSE Computer Application - Class X - MCQ - CALCUTTA PUBLIC SCHOOL

Q Predict the output of the following Java code:

class MCQ
{
	public static void main(String args[])
	{
		MCQ mcq = new MCQ();
		mcq.test(12);
	}

	void test(int n){

		for(int x= 1; x <= n; x++)
		  if(n%x == 0)
		    System.out.print(x+" ");
	}
}

Question ID
#22359
Subchapter
ICSE Computer Application - Class X - MCQ - CALCUTTA PUBLIC SCHOOL
Action
Choose one option below

Choose Your Answer

Click an option to check whether your answer is correct.

  • A 1 2 3 4 6 12
  • B 1 2 3 4 6 12 13
  • C 1 2 4 6 12
  • D 1 2 3 6 12
Correct Answer: A

Explanation

  • Class and Main Method:

    • The class MCQ contains the main method, which is the entry point for the program.
    • Inside the main method, an instance of MCQ is created, and the test method is called with the argument 12.
  • Method test:

    • The test method takes an integer n as a parameter.
    • It iterates through numbers from 1 to n (inclusive) using a for loop.
    • Inside the loop, it checks if n is divisible by x using the condition if (n % x == 0).
    • If the condition is true, it prints the value of x followed by a space.
  • Output Calculation:

    • The test method is called with n = 12.
    • The loop iterates from 1 to 12 and checks for divisibility.
    • The numbers that divide 12 without leaving a remainder (i.e., the factors of 12) are 1, 2, 3, 4, 6, and 12.
Iteration x Value Condition x <= n Condition n % x == 0 Action
1 1 true true Print 1
2 2 true true Print 2
3 3 true true Print 3
4 4 true true Print 4
5 5 true false Do nothing
6 6 true true Print 6
7 7 true false Do nothing
8 8 true false Do nothing
9 9 true false Do nothing
10 10 true false Do nothing
11 11 true false Do nothing
12 12 true true Print 12
13 13 false - Loop ends

Share This Question

Share this MCQ with your friends or study group.