Here I have a simple algorithm that computes the square of a number by adding up all of the odd numbers equal to the inputted number, such that:
1 = 1 = 1-squared
1 + 3 = 4 = 2-squared
1 + 3 + 5 = 9 = 3-squared
and so forth. The algorithm is as follows:
int triangleSquare(int number) {
int product = 0;
int currentOdd = 1;
while (number--) {
product += currentOdd;
currentOdd += 2;
}
return product;
}
My question is about the segment:
while (number--) { ... }
For some reason I get different results between while (--number)
and while (number--)
, which I assume is because --number
should decrement first before performing the while loop (and vice-versa for number--
). My question is, why does it make a difference? Shouldn't the while loop always execute last, regardless of the increment order? I must be missing something obvious, but that seems very odd to me, almost as though number--
makes the conditional behave like a do {...} while()
loop.