This is an exemplary program in AP Computer Science, and I cannot understand the flow of control over 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 ); }
He 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 through:
mystery( n - 1 );
However, I do not see how it can output these five statements after:
n is zero so no more recursive calls!
Logically, it looks like it will only indicate:
We did it again with n = 0
Can someone help the student and explain to me how he deduces what he did?
source share