Given the following recursive function, what would be printed by mysterious(4)?
void mysterious(int x) {
if (x == 0) return;
printf(“%d ”, x);
mysterious(x-1);
mysterious(x-1);
}
Here is my call stack:
mysterious(4) => print 4
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(0) => print 0
Is this correct?
Why don’t you just type it in to an editor in your language of choice, compile it and run? I chose Java but that’s just because I’m between CygWin installs on my box at the moment – I’d much rather be using C 🙂
This outputs the numbers:
Basically, what’s happening is that, at each level, you print out the number then call the next level twice with the next lowest number (unless it’s reached zero).
The following diagram will hopefully illustrate this better, with different symbols representing different layers: