Bird
0
0

What is the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Arrays
What is the output of the following Java code?
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < nums.length; i++) {
    sum += nums[i];
}
System.out.println(sum);
A15
B10
C5
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand the array and loop

    The array nums contains 1, 2, 3, 4, 5. The loop runs from i=0 to i=4 (nums.length is 5).
  2. Step 2: Calculate the sum of all elements

    sum = 0 + 1 + 2 + 3 + 4 + 5 = 15.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Sum of 1 to 5 = 15 [OK]
Quick Trick: Sum array by adding all elements in a loop [OK]
Common Mistakes:
  • Off-by-one error in loop
  • Starting sum at wrong value
  • Using wrong loop condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes