nerdexam
Oracle

1Z0-803 · Question #233

Given: public class TestLoop1 { public static void main(String[] args) { int a = 0, z=10; while (a < z) { a++; --z; } System.out.print(a + " : " + z); } } What is the result?

The correct answer is A. 5 : 5. The code uses a while loop with two integer variables, one incrementing and one decrementing, to show how a loop terminates when a condition based on their relative values becomes false.

Using Loop Constructs

Question

Given:

public class TestLoop1 { public static void main(String[] args) { int a = 0, z=10; while (a < z) { a++; --z; } System.out.print(a + " : " + z); } } What is the result?

Options

  • A5 : 5
  • B6 : 4
  • C6 : 5
  • D5 : 4

How the community answered

(52 responses)
  • A
    73% (38)
  • B
    10% (5)
  • C
    4% (2)
  • D
    13% (7)

Why each option

The code uses a while loop with two integer variables, one incrementing and one decrementing, to show how a loop terminates when a condition based on their relative values becomes false.

A5 : 5Correct

The loop starts with `a=0` and `z=10`. In each iteration, `a` increments by 1 and `z` decrements by 1. The loop continues as long as `a < z`. They will meet when `a` reaches 5 and `z` reaches 5, at which point the condition `a < z` (5 < 5) becomes false, and the loop terminates, printing their final values.

B6 : 4

This result would imply the loop executed one more time than it should have or the values were miscalculated, as `a` and `z` would not simultaneously be 6 and 4 at termination.

C6 : 5

This output implies an incorrect number of loop iterations or miscalculation of `a` or `z`'s final value.

D5 : 4

This result suggests an off-by-one error in tracking `a` or `z` during the loop execution, inconsistent with the symmetric increment/decrement until `a < z` is false.

Concept tested: While loop execution, increment/decrement operators, loop termination

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

Topics

#while loop#increment operator#decrement operator#loop tracing

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice