pls help me trace my final exam

#include<iostream>

using namespace std;
int main()
{
int i, k, ans=0;
for(i=1; i<=4; i+=2)
{
for(k=1; k<=i; k++)
{
ans = 2*i*k;
}
}
cout << ans;

return 0;
}


the answer is 18. please teach me how to trace why it is 18.
Sure, initially all var's are 0.

1.) Outer for loop, remember i =1.. continue to inner loop
2.) Inner for loop, remember k = 1 and is <= to i (1)
so ans = 2 * i(1) * k(1) = 2

3.) start over from outer loop

4.) i = i(1) + 2 = 3 (because the i+=2 in the for loop says to do this every iteration)
5.) k = 1 so..
6.) ans = 2 * i(3) * 1 = 6

k is now <= i(3) so...
7.) k = 1 so add one to it. Now, k = 2
8.) ans = 2 * i(3) * k(2) = 12

k is still <= i(3) so..
9.) k = 2 so add one to it. Now, k = 3
10.) ans = 2 * i(3) * k(3) = ANSWER(18)
Last edited on
thanks you so much.
Topic archived. No new replies allowed.