First, something simple to keep in mind is that, when you write recurrent functions, if you write the call to itself at the end, the compiler can optimize it, so it doesnt eat more and more stack with each call. Its called tail-call optimization/elimination.
Second, you need to put 2^n, not 2*n, also, the order in which you print the asterisks doesnt matter.
If I could use two functions, I would do that, it i obvious, but otherwise something like this should do:
static void printPowerOfTwoStars(int x)
if (x > 0) x = -(1 << x);
putchar(*);
if (++x < 0) printPowerOfTwoStars(x);
Of course there are many other way, but thi one i pretty clean :). I guess it doesnt need much explanation, but just in case: it use negative values to encode iterations, and the (1 << n) is a way to calculate 2^n, using binary arithmetic.
|