Is there some sort of efficient mathematical way by which someone can know what the following will print without testing it on a computer, or going through and doing all 40 iterations manually? (The answer is "132," but I am trying to see if there is a way to do it mathematically and without the computer).
1 2 3 4 5 6
int n = 10;
for (int i = 0; i < 40; ++i)
{
n = n + 3;
}
cout << n + 2;
I don't know if there's any way to methodically automate the conversion of such algorithms.
However, just a little thought gave me the expression 10 + 3*40 + 2 which gives 132.
Some algorithms involving a series of numbers, such as finding the sum of a series often have established mathematical formulae too.
But not all code is so conveniently classified. Sometimes one will have to step through it line by line (working on paper), to arrive at the expected result.
2. for (int i = 0; i < 40; ++i) n = n + 3 ;
is n = n + 3 ; repeated 40 times (unroll loop)
equivalent to n = n + 120 ;
equivalent to n = 10 + 120 ; (constant folding)
equivalent to n = 130 ;
3. cout << n + 2;
equivalent to cout << 130 + 2 ; (constant folding)
equivalent to cout << 132 ;
optimise: elide n, generate code "as-if" we had written cout << 132 ;
Thank you very much! That makes sense. So the way I should approach such problems is to think how the loop affects the value of the integer outside of its scope. So if I had
1 2 3 4 5 6
int n = 5;
for (int i = 0; i < 40; ++i)
{
n = n -3;
}
cout << n + 2;
I would ask myself how the loop affects the value of the relevant integer outside of its scope, which is 'n' in this case. The answer here is that the loop subtracts 120 (40 x -3). So to find the answer to the above, it would be 5 - 120 + 2 = -113. Thanks to all, I appreciate the help!