For Loop Summation Error
The following code segment is intended to compute the sum of the integers from 1 to 10. However, it fails to produce the correct result due to a logical error. Which statement best explains this error?
public class SumError {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
A
The loop’s termination condition ‘i < 10’ mistakenly excludes the number 10, resulting in an incorrect sum.
B
The loop should be a while loop instead of a for loop to correctly accumulate the sum.
C
The print statement is incorrectly placed, causing the sum to be printed multiple times.
D
The variable ‘sum’ should be initialized to 1 instead of 0.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE