Given the following code, where x = 0, what is the resulting value of x after the for-loop terminates?


Given the following code, where x = 0, what is the resulting value of x after the for-loop terminates?


for(int i=0;i<5;i++)


x += i;

a) 0

b) 4

c) 5

d) 10

e) 15

Answer: d. Explanation: Each pass through the for-loop results with the current value of the loop index, i, being added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x + 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3 = 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10.