final exam - please help whats the output/answer of this prob.

int i, k, ans=0;
for(i=1, i<=4; i+=2)
{
for(k=1; k<=i; k++)
{
ans = 2*i*k;
}
}
cout << ans;
}
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
int i, k, ans=0;

for(i=1, i<=4; i+=2)
{
	for(k=1; k<=i; k++)
	{
		ans = 2*i*k;
		}
		}
		cout << ans;
	}
}
"}" in line 8 and 9 are missing "{"
#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.
just use a debugger and run through the loops
Like what Darkmaster suggested, use a debugger.

But I can explain why the answer is 18.

You output the result at the end of 2 loops. So you got to see the value for both i and k for the last loop. In this case, i will be 1 and 3, k will be 1 and 3. So the last values for i and k are 3 and 3 respectively.

So the answer will be 2*3*3 = 18.
thanks you
osgwsy (14)
go through it in your head (if you UNDERSTAND IT) and you will know... try to understand this stuff, don't be a brain-dead idiot like the ones I see all the time... "herp derp... I DUNNO, who cares??"

It's a higher education because it's usefull to know all of the material you're being taught at that higher level.

Don't brush by all of it, not remembering it later. I have to assume you have learned this in class since you're taking an exam on it.
Topic archived. No new replies allowed.