Reputation: 19
This is a question from a practice test that I do not fully understand.
For the code fragment
int i = 0, j = 0, k = 0;
for (i=-1; i<=10; ++i){
j = i; ++k;
}
I am asked to find the values of the variables after executing the code.
The answers are:
i = 11 j = 10 k = 12
I don't understand how, can someone please help?
Upvotes: 1
Views: 171
Reputation: 1175
Take three variables separate. You can see the variable k would be incremented , the number of times the loop is executed. The no. of time sit would be executed from -1 to 10 it would have done 12 iterations
k = 1, i = -1, j=-1
k = 2, i = 0, j=0
k = 3, i = 1, j=1
k = 4, i = 2, j=2
k = 5, i = 3, j=3
k = 6, i = 4, j=4
k = 7, i = 5, j=5
k = 8, i = 6, j=6
k = 9, i = 7, j=7
k = 10, i = 8, j=8
k = 11, i = 9, j=9
k = 12, i = 10, j=10
After This i has reached its limit, but it will first increment and then check, hence i=11, k=12 and j to a one less than the value of i i.e j= 10
Upvotes: 2
Reputation: 16406
Understanding the value of i
after the loop is very simple, much simpler than the sorts of other answers here. The loop condition is i<=10
... in order for the loop to terminate, that condition must be false. Clearly, the value of i
that makes that false is 11.
The value of j
at the end of the loop is the previous value of i
, which is 10, and the value of k
is the number of times the loop executed, which is 1 (for -1) + 1 (for 0) + 10 (for 1 thru 10) = 12.
Upvotes: 5
Reputation: 7917
Here are the steps:
i
to minus 1. i <= 10
is true, so loop is entered. j
is set to i
, so j
is also minus 1.k
is incremented, so k
becomes 1.i
is incremented because of the ++i
, so i
becomes 0.i
is zero, i <= 10
is true, so the loop is entered again.In this way, the loop continues, changing j
, k
, and i
in that order. So when i
becomes 10, j
will be 9 and k
11. At that point:
j
becomes 10 as well; k
becomes 12i
gets incremented to 11. The loop condition i <= 10
is false, and the loop terminates.So i
is 11. j
is 10, k
is 12 when the loop terminates.
The key point is, after the first pass, every time the loop is entered, j
is one less than i
, and k
is one greater than i
. When the loop terminates, this is still the case.
Upvotes: 3
Reputation: 2857
for (i=-1; i<=10; ++i){
j = i; ++k;
}
Here is the loop :
i = i +1; <-------+
| |
check condition!------|--+
| | |
j = i; | |
| | |
k++;----------------+ |
| |
+<--------------------+
|
other code
at last loop
i = 10
condition == true
j = 10;
k = 12;
Then
i= i+1
means i = 11
but the condition show false! loop end.
Upvotes: 2
Reputation: 3421
i must be <= 10, so it is 11 to exit the loop and inside the last iteration of the loop, i = 10 = j. k is 1 after the first iteration, while i is -1. Running through the loop, you'll see:
k = 1, i = -1
k = 2, i = 0
k = 3, i = 1
k = 4, i = 2
k = 5, i = 3
k = 6, i = 4
k = 7, i = 5
k = 8, i = 6
k = 9, i = 7
k = 10, i = 8
k = 11, i = 9
k = 12, i = 10
Therefore k = 12
Upvotes: 3