Sunday, April 29, 2012

9.31

Here is a legal switch-statement in C/C++

int n = ...;
int q = (n +3) / 4;
switch (n % 4)
{
case 0: do { n++;
case 3: n++;
case 2: n++; 
case 1: n++; 
}while (--q > 0);
}



Suppose that n has the value (a) 0; (b) 1; (c) 5; (d) 8. What is the value of n in each case after the execution of the above switch-statement? Can you state a general rule for the value of n after this code executes? If so, state it. If not, explain why not.

(a) 0
n = 4

(b) 1
n = 2

(c) 5
n = 10

(d) 8 
n = 16

General rule:


if(n>0) output = 2*n
if(n==0) output = 4
if(n<0) output = n

No comments:

Post a Comment