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…
Question
Options
- Acount = (count++)+1;
- Bcount = count++;
- Ccount += 2;
- Dcount += 2;
How the community answered
(25 responses)- A8% (2)
- B16% (4)
- C4% (1)
- D72% (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
Community Discussion
No community discussion yet for this question.