That means odd has already poses 2 values !! Because it says start from "odd" , so "odd "
start adding 1 because of " odd ++ " and then add another 1 from " +1 " ...
Then , the next , " odd " add another 1 first because of "odd++" and then "number ++ " execute , adding " number" to 1 , then plus one equals to 5 !!
The heck , so mess !! ... so tough for learning programming code .... |
Ah. I think I see the problem. You aren't interpreting the code correctly. Here is the code again (and slightly reformatted):
1 2 3 4 5 6 7 8
|
int odd = 0;
int number = 0;
while ( number <= 10 )
{
odd = odd + number + 1 ;
odd ++ ;
number ++ ;
}
|
The important thing you may be missing is that
the code gets executed in a specific order, one line after another. Odd does NOT possess two values at any one time. And it doesn't "start adding 1 because of odd++". This code executes as follows:
First, lines 1 and 2 define variables
odd and
number and assigned 0 to each of them.
Then line 3 executes for the first time. Since
number is zero, the expression is true and execution proceeds to line 5.
Line 5 executes.
odd+number+1 is 0+0+1 so it assigns 1 to
odd. Note that it evaluates the right side of the assignment first, using the existing value of
odd. Then it assigns the value of the expression to the left side, which happens to be
odd.
Lines 6 executes, incrementing
odd to 2.
Next line 7 executes, incrementing
number to 1.
Next the program goes back up and executes line 3 again. At this point
number is 2 so the expression is true and execution proceeds to line 5.
Next line 5 executes again. This time
odd+number+1 is 2+1+1, so it assigns 4 to
odd.
Line 6 executes, incrementing
odd to 5.
Line 7 executes, incrementing
number to 2.
Next execution goes back to line 3.
Number is still less than 10.
Do you see how this works? The lines execute in a specific order.
This time through the loop it sets
odd to 5+2+1=8, then increments
odd to 9 and increments
number to 3.
Next time it sets
odd to 9+3+1=13, increments it to 14 and increments
number to 4.
And so on until eventually
number is 11 when it executes line 3. At that point, the condition is false, and execution goes to the statement after the loop.
I hope this helps.