Thursday, January 15, 2009

C Up your skills!!

Debug the following program. What does the debugged program do?

#include
#define REP(t,n) for(t=n;t;t--,t&=n)
typedef int *abc(int a);
int func(int n)
{
int t;
REP(t,n)
printf("%3d",t);
return 0;
}
int main()
{
int n=9;
abc f1;
f1=func;
f1(n);
return 0;
}


Well this is one of the best questions i have ever came across( in terms of trick they have :P )!

First part first: the error.


Well u wud not notice but it is sorta syntactical error... and such codes are sometimes called obfuscated codes!!

Well for the first part the error lies in typedef.... statement:

Correct form: typedef int (*abc)(int a);

because else the precedence will say somethin else, it'll take int * and typedef to abc(int a) which is weird, i dont know how the code for this line even compiled.... by the way it's C, so u expect obfuscation a lot :P!!

But the next intersting part..... how shall u guess what the program is doin.

First the macro can be put directly in int func(...), to get:

nt func(int n)
{
int t;
for(t=n;t;t--,t&=n)
printf("%3d",t);
return 0;
}


so we actually get a for loop... interesting hmmmmm.

But thats the simpler part.... take this.... the output: n=9
o/p: 9 8 1

Now u really dont get much hints from here.... if u do.... then why the heck u DONT participate in the event :P

And now some more outputs for the interest!

n:88
0/p: 88 80 72 64 24 16 8

in:31
o/p: 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

in:45
o/p: 45 44 41 40 37 36 33 32 13 12 9 8 5 4 1

Now let's notice the similarity: count the total num of terms,

n=9 t=3
n=88 t=7
n=31 t=31
n=45 t=15

Whats so intersting, all are of the form 2^k-1

Hmmm so whats boiling.... let's take binary of 9
9==1001

Now if i take all combination of 0's and 1's in the place of 1's of the bin number, we get:
0000(redundant)
0001
1000
1001

Voila it's the series..... didnt get it... just convert them to decimals!

Similarly let's take: 31

31==11111

Now if u'll take all ppossible combination of 0's and 1's in place of 1's in 31( actually all are one's ), u'll get all numbers from 0-31( 0, is excluded by defualt ), and thats the answer actually!

Hence the result

Hope u njoyed the question.........

No comments:

Post a Comment