- /**Recursion Demo 3
- * @author TK Rogers
- * @version 11-06-09
- */
- public class
Mystry {
-
- public
static void main ( ) {
-
System.out.println ( mystry ( 3 ) ) ;
- }
-
-
public static int mystry ( int y ) {
-
System.out.println ( " y = " + y ) ;
- if
(y == 0) {
- System.out.println (
" return x = " + 1 ) ;
-
return 1 ;
- } else {
-
System.out.println ( " else" ) ;
-
int x = mystry ( y / 2 ) ; // y/2 is integer math so if y=3,
y/2 = 1
-
//
y = 3 is stored in a stack and the method is re-run
with y = 1
-
// y = 1 is stored in a stack and the method is re-run with
y = 0
-
// y = 0
is stored in a stack the recursion stops and returns 1,
-
// so that x = 1.The method then continues.
-
-
System.out.println ( " x = " + x ) ;
-
x *= x ;
-
if ( y % 2 == 1 ) x *= 3 ; // % is a modulus operator. It
returns the
-
// remainder of a division process.
example 1: 3 % 2 = 1
because 2
- // goes into
3 once with a remainder of 1,
example 2:
5 % 2 = 1
- // because 2 goes into 5 twice
with a remainder of 1,
- //
example 3:
4 % 2 = 0
-
- System.out.println (
"return x = " + x ) ;
-
return x ;
- // The
program now starts to use the y-values stored in the stack.
-
// 1st time through
y = 0, x = 1
-
// 2nd time through y = 1,
x = 3
-
// 2nd time through y = 3,
x = 27
-
// The stack with y values is now empty and the program quits,
-
// having returned 27 back to the point where the method was
-
// originally called.
- }
- }
- }