10
Dale Robert CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Embed Size (px)

Citation preview

Page 1: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

CSCI N305

Functions Recursion

Department of Computer and Information Science,School of Science, IUPUI

Page 2: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

RecursionRecursion

Recursive functions A function can invoke any other function; A function can invoke any other function; “ Can a function invoke “ Can a function invoke itself?”itself?”Functions that call themselves either directly or indirectly (through Functions that call themselves either directly or indirectly (through another function) is called a another function) is called a recursive functionrecursive function..If a function is called with a simple case, the function actually knows If a function is called with a simple case, the function actually knows how to solve the simplest case(s) - “how to solve the simplest case(s) - “base casebase case” and simply returns a ” and simply returns a result.result.If a function is called with a complex case - “If a function is called with a complex case - “recursive caserecursive case” , it invokes ” , it invokes itself again with simpler actual parameters.itself again with simpler actual parameters.

1.1. must resembles original problem but slightly simplifiedmust resembles original problem but slightly simplified2.2. function will call itself (recursion step or recursive call) to solve slightly function will call itself (recursion step or recursive call) to solve slightly

simplified problemsimplified problem3.3. process continues until the last recursive call is with the base caseprocess continues until the last recursive call is with the base case4.4. that call returns the result of the base casethat call returns the result of the base case5.5. return to previous calling functionsreturn to previous calling functions6.6. finally reaches main.c.finally reaches main.c.

Eventually base case gets solvedEventually base case gets solvedGets plugged in, works its way up and solves whole problemGets plugged in, works its way up and solves whole problem

Page 3: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Recursion Recursion (cont.)(cont.)

ExampleExample: Compute : Compute x x yy for for x x > 0> 0 & & y y > 0> 0x y = x * x * x * … * x

base case: x1 = x

x y = x1 * ( x * x * … * x)= x1 * ( x1 * ( x * x * … * x ))= x1 * ( x1 * ( x1 * ( x * x * … * x )))= x1 * x y-1

ex. x 4 = x1 * ( x1 * ( x1 * ( x1 )))

Fundamental rules of recursionFundamental rules of recursion1.) Base cases1.) Base cases2.) Making progress through recursion2.) Making progress through recursion3.) Design rule: assuming all recursive call work (details hidden)3.) Design rule: assuming all recursive call work (details hidden)4.) Always specify the base case; otherwise, indefinite recursive will 4.) Always specify the base case; otherwise, indefinite recursive will

occur and cause “occur and cause “stack-overflowstack-overflow” error.” error.

x1

x1

x1

x1

*

*

*x1

x3

x2

x1

x2

x3

x4x4

5

51

51

51

*

*

*51

53

52

x1

x2

125

62554

25

5

y times

Page 4: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Recursion: #include <stdio.h>

int x_pow_y(int, int);

main(){ printf(“enter x and y: \n”); scanf(“%d, %d”, x, y); z = x_pow_y(x,y); printf(“z: %d\n”, z);}

x_pow_y(int a, int b){ if (b==1)

return a; else

return (a * x_pow_y(a, b-1)) }

Recursion vs. IterationRecursion vs. Iteration

Iteration: x_pow_y = 1;

for (i = y; i >=1; i--) x_pow_y*=x;

If x = 5, y = 4

x_pow_y = 1, x = 5, y = 4, i = 4;1.) x_pow_y = 5*1 = 5, i = 3;2.) x_pow_y = 5*5 = 25, i = 2;3.) x_pow_y = 25*5 = 125, i = 1;4.) x_pow_y = 125*5 = 625, i = 0;

…x=5;y=4;

x_pow_y(5,4);

…is (4==1)?

no

…is (3==1)?

no

…is (2==1)?

no

…is (1==1)?

yes

return 5

x_pow_y(5,4) x_pow_y(5,3) x_pow_y(5,2) x_pow_y(5,1)

Base Casemain5

25125625

Page 5: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Example Using Recursion: FactorialExample Using Recursion: Factorial

Example: factorials: 5! = 5 * 4 * 3 * 2 * 1Notice thatNotice that

5! = 5 * 4!5! = 5 * 4!4! = 4 * 3! 4! = 4 * 3! ……

Can compute factorials recursively Can compute factorials recursively Solve base case (Solve base case (1! = 0! = 11! = 0! = 1) then plug in) then plug in

2! = 2 * 1! = 2 * 1 = 2;2! = 2 * 1! = 2 * 1 = 2;3! = 3 * 2! = 3 * 2 = 6;3! = 3 * 2! = 3 * 2 = 6;

long factorial(int n)long factorial(int n){{

if (n <= 1)if (n <= 1)return 1;return 1;

elseelsereturn n * factorial(n-1);return n * factorial(n-1);

}}

 

0

0

)!1(

1!

n

n

nnn

Page 6: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Example Using Recursion: The Fibonacci SeriesExample Using Recursion: The Fibonacci Series

Example: Fibonacci series:

FFk k = = FFk-1 k-1 + + FFk-2k-2,, FF0 0 = 1, = 1, FF11 = 1 ex: 0, = 1 ex: 0, 1, 1, 2, 3, 5, 8…1, 1, 2, 3, 5, 8…

Each number is the sum of the previous two Each number is the sum of the previous two Can be solved recursively:Can be solved recursively:fib( n ) = fib( n - 1 ) + fib( n – 2 )fib( n ) = fib( n - 1 ) + fib( n – 2 )

Set of recursive calls to function Set of recursive calls to function fibonaccifibonacciCode for the Code for the fibonaccifibonacci function function

long fibonacci(long n)long fibonacci(long n){{ if (n <= 1)if (n <= 1) return n;return n;else;else;return return fibonaccifibonacci(n-1) + (n-1) + fibonaccifibonacci(n-2);(n-2);

}}

f( 3 )

f( 1 )f( 2 )

f( 1 ) f( 0 ) return 1

return 1 return 0

return +

+return

 

Page 7: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

1 /* Fig. 5.15: fig05_15.c2 Recursive fibonacci function */3 #include <stdio.h>45 long fibonacci( long );67 int main()8 {9 long result, number;1011 printf( "Enter an integer: " );12 scanf( "%ld", &number );13 result = fibonacci( number );14 printf( "Fibonacci( %ld ) = %ld\n", number, result );15 return 0;16 }1718 /* Recursive definition of function fibonacci */19 long fibonacci( long n )20 {21 if ( n == 0 || n == 1 )22 return n;23 else24 return fibonacci( n - 1 ) + fibonacci( n - 2 );25 }

Enter an integer: 0Fibonacci(0) = 0 Enter an integer: 1Fibonacci(1) = 1

Enter an integer: 2Fibonacci(2) = 1 Enter an integer: 3Fibonacci(3) = 2 Enter an integer: 4Fibonacci(4) = 3 Enter an integer: 5Fibonacci(5) = 5 Enter an integer: 6Fibonacci(6) = 8 Enter an integer: 10Fibonacci(10) = 55 Enter an integer: 20Fibonacci(20) = 6765 Enter an integer: 30Fibonacci(30) = 832040 Enter an integer: 35Fibonacci(35) = 9227465

1. Function prototype

2. Declare variables

3. Input an integer

4. Call function fibonacci

5. Output results.

6. Define fibonacci recursively

Page 8: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Recursion vs. IterationRecursion vs. Iteration

Both are based on the control structuresBoth are based on the control structuresRepetition (Iteration): explicitly uses repetition (loop).Repetition (Iteration): explicitly uses repetition (loop).Selection (Recursion): implicitly use repetition by Selection (Recursion): implicitly use repetition by successive function callssuccessive function calls

Both involve terminationBoth involve terminationIteration: loop condition failsIteration: loop condition failsRecursion: base case recognizedRecursion: base case recognized

Both can lead infinite loopsBoth can lead infinite loopsLoop termination is not metLoop termination is not metBase case is not reachedBase case is not reached

Balance Balance Choice between performance (iteration) and good software Choice between performance (iteration) and good software engineering (recursion)engineering (recursion)

Page 9: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Recursion vs. IterationRecursion vs. IterationAny problem that can be solved recursively can also be Any problem that can be solved recursively can also be solved iteratively with a stack. A recursion is chosen in solved iteratively with a stack. A recursion is chosen in preference over iteration while the recursive approach preference over iteration while the recursive approach more naturally mirrors the problem and results in a more naturally mirrors the problem and results in a program that easier to understand and debug.program that easier to understand and debug.

Recursion has an overhead of repeated function calls Recursion has an overhead of repeated function calls which is expensive in terms of processor time and which is expensive in terms of processor time and memory usage.memory usage.

Another reason to choose recursion is that an iterative Another reason to choose recursion is that an iterative solution may not apparent.solution may not apparent.

If used properly a recursive approach can lead to smaller If used properly a recursive approach can lead to smaller code size and elegant program (at the case of code size and elegant program (at the case of performance penalty.)performance penalty.)

Page 10: Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

AcknowledgementsAcknowledgements