Question:

What will be the output of the following Java program? verbatim class Output public static void main(String args[]) int arr[] = 1, 2, 3, 4, 5; for (int i = 0; i < arr.length - 2; ++i) System.out.println(arr[i] + " "); verbatim

Show Hint

Pay close attention to the loop termination condition. A common mistake is to misinterpret conditions like `i < length` versus `i <= length` or expressions like `length - 2`. Carefully trace the loop for the first and last valid index values.
Updated On: Jul 2, 2026
  • 1 2
  • 1 2 3
  • 1 2 3 4
  • 1 2 3 4 5
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is B

Solution and Explanation

Let's analyze the `for` loop in the given Java code.
1. `int arr[] = 1, 2, 3, 4, 5;`: An integer array `arr` is initialized. The length of the array, `arr.length`, is 5.
2. The loop condition is `i < arr.length - 2`. Substituting the length, the condition becomes `i < 5 - 2`, which simplifies to `i < 3`.
3. The loop will execute for the values of `i` that satisfy this condition, starting from `i = 0`. The values will be `i = 0`, `i = 1`, and `i = 2`.
4. Inside the loop, `System.out.println(arr[i] + " ");` prints the element at index `i` followed by a space, and then moves to a new line.
When `i = 0`: It prints `arr[0]` which is 1. Output: `1 ` When `i = 1`: It prints `arr[1]` which is 2. Output: `2 ` When `i = 2`: It prints `arr[2]` which is 3. Output: `3 `
5. When `i` becomes 3, the condition `3 < 3` is false, and the loop terminates.
The final output will be the numbers 1, 2, and 3, each on a new line because of `println`. However, the options present the output on a single line. Assuming `print` was intended instead of `println`, the output would be `1 2 3 `. Option (B) represents the sequence of numbers printed.
Was this answer helpful?
0
0