0
Who can describe the result? And quantity of iteration?
int value=0; for (int i=0;i <7;i++){ value+=i%2; } cout<<value;
3 Respuestas
+ 2
value gets increased by 1 every time i is an odd number. The for-loop runs from i = 0 to i = 6, that's 3 odd numbers (1,3,5), so the output will be 3.
Note: i%2 is always 1 for odd and 0 for even numbers.
+ 2
The output is 3
Why?
Loop:
1 -> i = 0, i % 2 = 0, value = value(0) + 0
2 -> i = 1, i % 2 = 1, value = value(0) + 1
3 -> i = 2, i%2 = 0, value = value(1) + 0
4 -> i = 3, i % 2 = 1, value = value(1) + 1
...
For every even integer, i % 2 will be 0.
For every odd one, i % 2 will be 1
Now you have to think:
How many odd numbers are there between 0 and 6 (i < 7)
Ans: 3 (1, 3, 5)
So, we will add 1 to value 3 times
0
thank you very very much!