nerdexam
Oracle

1Z0-811 · Question #59

Given the code fragment: int count = 0; while (count <= 10) { System.out.print (count + " "); / line n1 / } Which statement, when inserted at line n1, enables the code to print 0 2 4 6 8 10?

The correct answer is D. count += 2. count += 2 correctly increments count by 2 on each iteration, producing the sequence 0, 2, 4, 6, 8, 10 before count reaches 12 and exits the <= 10 condition. Option A (count = (count++)+1) uses post-increment: count++ returns the old value before incrementing, so the net effect…

Control Flow

Question

Given the code fragment: int count = 0; while (count <= 10) { System.out.print (count + " "); /* line n1 */ } Which statement, when inserted at line n1, enables the code to print 0 2 4 6 8 10?

Options

  • Acount = (count++)+1;
  • Bcount = count++;
  • Ccount += 2;
  • Dcount += 2;

How the community answered

(25 responses)
  • A
    8% (2)
  • B
    16% (4)
  • C
    4% (1)
  • D
    72% (18)

Explanation

count += 2 correctly increments count by 2 on each iteration, producing the sequence 0, 2, 4, 6, 8, 10 before count reaches 12 and exits the <= 10 condition. Option A (count = (count++)+1) uses post-increment: count++ returns the old value before incrementing, so the net effect is only +1 per iteration, printing every integer 0–10. Option B (count = count++) is an infinite loop trap - count++ returns the pre-increment value and assigns it back, so the side-effect increment is immediately overwritten and count never changes. Note that as written, C and D are identical - this appears to be a transcription error in the question (C is likely meant to be something like count = count + 2 or count =+ 2).

Memory tip: When you see count = count++ on an exam, think "infinite loop" - the assignment always clobbers the increment. And += is the clean, unambiguous way to accumulate a value; prefer it over post-increment tricks in loop bodies.

Topics

#while loops#post-increment operator#compound assignment#loop control

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice