print 1 to 100 without using recursion and conditions
C (90) (79) (59) (47) (42) (40)
static int
x=1;a(){char b[8];printf("%d\n",x++);b[24]-=5*(1-x/101);}main(){a();return 0;}
The function a
which prints the numbers does not call itself! I exploited a buffer overflow and changed the return address to make the program counter go over function a
again as long as I need.
I don't know if this is considered to be a recursion, but I thought it would worth trying.
This code works on my 64-bit machines with gcc 4.6, for other platforms the last statement of function a
, could be a little different.
Exp1: I allocated a dummy buffer on stack b
, and then addressed a passed-by-end location, which is the location of return address. I anticipated the distance between start of buffer and return address location from disassembly of function a
.
Exp2: Expression 5*(1-x/101)
, is 5
for all x<=100
and 0
for x=101
. By looking at disassembly of main
(in my case), if you decrease the return address by 5, you will set the PC to calling point of a
again. In the updated codes, the return value of printf
is used for checking loop condition.
Update: After applying ugoren's suggestions and some other changes:
x;a(){int b[2];b[3*(printf("%d\n",++x)&2)]-=5;}main(){a();}
Update2: After Removing function a
:
x;main(){int b[2];b[6^printf("%d ",++x)&4]-=7;}
Update3:
x;main(b){(&b)[1|printf("%d ",++x)&2]-=7;}
Update4: Thanks to mbz :)
x;main(b){(&b)[3|printf("%d ",++x)]-=7;}
85
C (gcc)
#define c printf("%d ",i++);
#define b c c c c c
#define a b b b b b
main(i){a a a a}
Assuming no command line arguments were passed.
C++ (159 136)
With templates.
#include<cstdio>
#define Z(A,B,C,D)template<A>struct P B{P(){C;printf("%d ",D);}};
Z(int N,,P<N-1>(),N)Z(,<1>,0,1)int main(){P<100>();}