Wednesday, December 08, 2004

C/C++: Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1

This question clearly specifies that 'if', 'for', 'while', etc are not allowed. I don't know how come 'if' is counted as a loop. But obviously the last resort to tackle this problem is to use recursive functions. Since 'if' is not allowed, I choose conditional operator and hopefully it is not against the rule, :-). My solution is:

#define max 100
#define min 1

int foo1(int bar)
{
(bar > min)? foo1(bar-1):1;
return printf("%d\n", bar);
}
int foo2(int bar)
{
(max > bar)? foo2(bar+1):1;
return printf("%d\n",bar);
}
int main(int argc, char* argv[])
{
foo1(max);
foo2(min);
return 0;
}

Recently I found someone posted an interesting solution for this problem on Slashdot. The recursion part is the easy part. The question is how to avoid the 'if'. Here is his/her idea [1]:

a(int c){printf("%d ",c);(c^100)&&a(c+1);}
b(int c){printf("%d ",c,(c^100)&&b(c+1));}
main(){a(1);puts("\n");b(1 );puts("\000");}

The method uses '&&' (Logical-AND) to define a stop condition for the recursion. Note that the expressions are evaluated from left to right. When the left part is false (0), the right part will not be evaluated, and this becomes the stop condition for the recursion. Similarly, we can also use '' (Logical-OR).

[1] http://developers.slashdot.org/comments.pl?sid=131673&cid=10995170

0 Comments:

Post a Comment

<< Home