nerdexam
Oracle

1Z0-803 · Question #263

Given the code fragment: for (int ii = 0; ii < 3;ii++) { int count = 0; for (int jj = 3; jj > 0; jj--) { if (ii == jj) { ++count; break; } } System.out.print(count); continue; } What is the result?

The correct answer is A. 011. The outer loop iterates from ii=0 to 2. Inside, count is reset to 0, and the inner loop iterates jj from 3 down to 1. count increments and the inner loop breaks only when ii equals jj, resulting in the printed output 011.

Using Loop Constructs

Question

Given the code fragment:

for (int ii = 0; ii < 3;ii++) { int count = 0; for (int jj = 3; jj > 0; jj--) { if (ii == jj) { ++count; break; } } System.out.print(count); continue; } What is the result?

Options

  • A011
  • B012
  • C123
  • D000

How the community answered

(36 responses)
  • A
    72% (26)
  • B
    17% (6)
  • C
    6% (2)
  • D
    6% (2)

Why each option

The outer loop iterates from `ii=0` to `2`. Inside, `count` is reset to 0, and the inner loop iterates `jj` from `3` down to `1`. `count` increments and the inner loop breaks only when `ii` equals `jj`, resulting in the printed output `011`.

A011Correct

When `ii=0`, no `jj` (3, 2, 1) matches, so `count` remains 0. When `ii=1`, `jj=1` matches, `count` becomes 1, and the inner loop breaks. When `ii=2`, `jj=2` matches, `count` becomes 1, and the inner loop breaks, leading to the output '011'.

B012

This output implies `count` became 2 for `ii=2`, which is incorrect because the inner loop breaks after the first match where `ii==jj`, causing `count` to be 1.

C123

This output implies `count` was 1 for `ii=0` and incremented multiple times for other `ii` values, which is incorrect as `count` is reset to 0 in each outer loop iteration and increments only once due to `break`.

D000

This output implies `count` never incremented, which is incorrect for `ii=1` and `ii=2` where `ii==jj` matches occur.

Concept tested: Java Nested Loops and Control Flow

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/loops.html

Topics

#Nested loops#Loop control statements#for loop#continue keyword

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice