34,548 views
42 votes
42 votes
Suppose that i and j are both of type int. What is the value of j after the following statement is executed?

for (i = 0, j = 0; i < 10; i++)
j += i;

User Mehul Sojitra
by
2.9k points

1 Answer

24 votes
24 votes

Answer:

The value of j after the above statement is executed would be 45.

The for loop initializes both i and j to 0, and then runs a loop that executes 10 times. Each time the loop runs, i is incremented by 1. The statement j += i adds the current value of i to j.

Since i starts at 0 and is incremented by 1 each time the loop runs, the values of i in each iteration of the loop are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The statement j += i adds these values to j in each iteration, so the final value of j after the loop is finished running is 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45.

User Naourass Derouichi
by
3.7k points