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
#define max 100
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