Reputation: 47
My book says for programming using while-loop, we must first initialize with a number, provide the condition mentioning 'while', and then it's to be followed by the statement to partake in the loop until the condition is met as well as to increment value in the loop. Example :
i = 1;
while(i<=10)
{
s = s + i;
p = p * i;
i++;
}
But, in case of summing of odd numbers program no such incrementing value has been shown. And, strangely enough(for me), I get correct result w/o the use of i++. I absolutely cannot wrap my head around why that is the case. Is mentioning i++ or i+1 not really a rule within loops?
int s, i, n;
s = 0;
i = 1;
while (i <= n)
{
s = s + i;
i = i + 2;
}
Upvotes: 0
Views: 1555
Reputation: 105
There is no such rule that we must use i++ in every loop(and for that matter using i as a loop variable).
As @Barmar indicated, you are incrementing i using the line :
i = i + 2;
There are cases where we need to increment by 3, 10, √n, logn, etc. There are even cases where we need to run a loop backwards hence, we decrement i.
The point is, the value of i must change at some point otherwise we'll end up in an infinite loop.
Upvotes: 0
Reputation: 781255
This line is the incrementing value:
i = i + 2;
The first loop increments by 1 with i++
. But since you only want the odd numbers, you need to increment by 2.
You can simplify this to:
i += 2;
Upvotes: 2