MCQ Single Best Answer Moderate

Q[Scope]
For the given code snippet, what will be the output?
int i;
for(i = 5; i >= 1; i--) {
    System.out.println();
}
System.out.println(i);

ID: #24934 Competency focused Practice Questions ISC Class XII Computer Science 4 views
Question Info
#24934Q ID
ModerateDifficulty
Competency focused Practice Questions ISC Class XII Computer ScienceTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A Zero will be displayed as variable i has local scope with respect to the loop.
  • B Zero will be displayed as variable i has global scope with respect to the loop.
  • C Error - Undeclared variable i.
  • D Output will be 1.
Correct Answer: Option B

Explanation

MCQ: Java Loop Scope Analysis

int i;
for(i = 5; i >= 1; i--) {
    System.out.println();
}
System.out.println(i);

Correct Answer:

(b) Zero will be displayed as variable i has global scope with respect to the loop.

Explanation:

In this code, the variable i is declared outside the for loop:

int i;

So, its scope is not limited to the loop. It remains accessible even after the loop ends.

The loop runs as follows:

  • i starts at 5
  • Condition checked: i >= 1
  • Inside loop: empty println executes
  • i is decremented each time (i--)

When i becomes 0, the condition i >= 1 fails and the loop stops.

At this point, the value of i is 0.

Finally, this statement executes:

System.out.println(i);

So the output will be:

Output: 0

Key Concept:

Variables declared outside a loop retain their updated value after the loop ends.

No Previous Next Question

Share This Question

Challenge a friend or share with your study group.