This is an example program in my AP Computer Science course, and I can't understand the flow of control of it.
public static void mystery( int n )
{
System.out.println( "mystery called with n = " + n );
if ( n == 0 )
{
System.out.println( "n is zero so no more recursive calls!" );
return;
}
mystery( n - 1 );
System.out.println( "We did it again with n = " + n );
}
public static void main( String[] args )
{
mystery( 5 );
}
It outputs this:
mystery called with n = 5
mystery called with n = 4
mystery called with n = 3
mystery called with n = 2
mystery called with n = 1
mystery called with n = 0
n is zero so no more recursive calls!
We did it again with n = 1
We did it again with n = 2
We did it again with n = 3
We did it again with n = 4
We did it again with n = 5
So far, I understand the recursive method and how it recalls itself via:
mystery( n - 1 );
However, I don't see how it can output those five statements after:
n is zero so no more recursive calls!
Logically, it seems like it would only state:
We did it again with n = 0
Can anyone help a student out and explain to me how it output what it did?
When a function finishes, the function that called it has the opportunity to complete and execute more code.
Here is an illustration of how this recursion happens. Each level of recursion is indicated by an increase in indentation.
mystery(5):
"mystery called with n = 5"
mystery(4):
"mystery called with n = 4"
mystery(3):
"mystery called with n = 3"
mystery(2):
"mystery called with n = 2"
mystery(1):
"mystery called with n = 1"
mystery(0):
"mystery called with n = 0"
"n is zero so no more recursive calls!"
mystery(0) returns
"We did it again with n = 1"
end of mystery(1)
"We did it again with n = 2"
end of mystery(2)
"We did it again with n = 3"
end of mystery(3)
"We did it again with n = 4"
end of mystery(4)
"We did it again with n = 5"
end of mystery(5)
After 'n is zero so no more recursive calls!' the method continues (the state is put on the stack and then loaded after the call to method(n-1) finishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With