MCQ Single Best Answer Easy

QPredict 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+" ");
	}
}

ID: #22359 ICSE Computer Application - Class X - MCQ - CALCUTTA PUBLIC SCHOOL 121 views
Question Info
#22359Q ID
EasyDifficulty
ICSE Computer Application - Class X - MCQ - CALCUTTA PUBLIC SCHOOLTopic

Choose the Best Option

Click any option to instantly check if you're 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: Option 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
No Previous No Next

Share This Question

Challenge a friend or share with your study group.