TRACING RECURSIVE METHODS Tracing Recursion How does it

  • Slides: 9
Download presentation
TRACING RECURSIVE METHODS

TRACING RECURSIVE METHODS

Tracing Recursion How does it work? Makes use of a data structure called a

Tracing Recursion How does it work? Makes use of a data structure called a stack. Last In, First Out (LIFO) Actions: Push (add element to top) Pop (remove element from the top)

In Recursion… Each method call is pushed onto the current stack. Numerous calls will

In Recursion… Each method call is pushed onto the current stack. Numerous calls will be pushed onto the stack until the base case is reached. The stack is then popped one element at a time (from the top), returning values/doing some task, until the original call is evaluated.

Example: void weirdo(int x){ if( x > 1 ){ weirdo(x/2); } System. out. print(x

Example: void weirdo(int x){ if( x > 1 ){ weirdo(x/2); } System. out. print(x + “ “); } What is the output of the call weirdo(40)?

Example: public int power(int base, int exp){ if(exp == 0) return 1; else return

Example: public int power(int base, int exp){ if(exp == 0) return 1; else return base * power(base, exp-1); } What is power(2, 4)?

int result = identity(10); System. out. println("The final answer is " + result); public

int result = identity(10); System. out. println("The final answer is " + result); public int identity(int num){ if(num < 1){ return 10; } else{ return num + identity(num - 2); } }

int result 2 = negative(-3); System. out. println("The final answer is " + result

int result 2 = negative(-3); System. out. println("The final answer is " + result 2); public int negative(int num){ if(num >= 20){ return -5; } else{ return negative(num + 4) + 2 * num; } }

void weirdo(int x){ if( x > 1 ){ weirdo(x/2); } System. out. print(x +

void weirdo(int x){ if( x > 1 ){ weirdo(x/2); } System. out. print(x + “ “); } What is the output of the call weirdo(40)?

void weirdom(int x){ System. out. print(x + “ “); if( x > 1 ){

void weirdom(int x){ System. out. print(x + “ “); if( x > 1 ){ weirdom(x/2); } } What is the output of the call weirdom(40)?