Programming problem

  • Thread starter Thread starter tuanl
  • Start date Start date
Joined
4/14/12
Messages
90
Points
18
I couldn't solve this programming problem. Hope someone on this forum can help me out:
What is the output of 5th line of this program?
Code:
int zebra(int x)
{
static int z = 0;
int z2 = 1;
int q = x + z + z2;
z += 1;
z2 += 1;
return q;
}
int main()
{
for (int i = 1; i <= 10; ++i) {
printf("%d\n", zebra(i));
}
return 0;
}

A. 4
B. 6
C. 8
D. 10
E. 12
 
The answer is B :)
Can you explain why? I thought the answer is D, since the function zebra(5)=int q=5+4+1=10. Notice that since z is static, z is initialized only once, so when i=5, z=4. Of course, z_2 is only 1 since it's initialized every time the function zebra(i) is called
 
My bad, you were right. I missed the z += 1 line (what a shame!) ! The exact answer really is D !
 
Back
Top