chapter 9: recursion1 chapter 9 recursion. recursion concept of recursion a recursive: benefit and...

26
Chapter 9: Recursion 1 CHAPTER 9 RECURSION

Upload: reynard-barker

Post on 30-Dec-2015

299 views

Category:

Documents


0 download

TRANSCRIPT

Chapter 9: Recursion 1

CHAPTER 9

RECURSION

Recursion Concept of recursion A recursive: Benefit and Cost Comparison : Iterative and recursive

functions Example : Simple and complex Converting recursive to non-recursive

equivalent functions

Chapter 9: Recursion 2

Chapter 9: Recursion 3

Simple Recursion Concept: defining a solution in terms of a

simpler version of the solution Recursion is often used instead of

iteration C permits a function to call itself. We say that a function is calling itself

when we can find a function call inside the body of the function with the same name as it has.

This function call is invoking itself.

Chapter 9: Recursion 4

What is a recursive solution? A solution of a problem is a recursive

solution if it is expressible in a smaller version of itself and if ultimately a simple non recursive solution can not be found.

A recursive technique is an alternative to iteration technique (using loop), a commonly used technique by student due to its simplicity.

Chapter 9: Recursion 5

A Recursive Solution In order to implement a recursion to solve a

problem, you need to consider some of these questions that are significantly useful: How can your problem being defined in term of smaller

version of itself ? How does each recursive call diminish the size of the

problem? What instance of the problem can serve as the case

base? As the problem size diminishes, will you reach the case

base?

A Recursive: Benefit & Cost

The Benefits: often your code will be shorter it is usually easier to define the solution recursively

and writing the code is just a matter of implementing the definition

more elegant solution you may not need local variables to implement your solution

(instead use parameter ‘passed by value’ properly) some solutions are only expressible recursively (or at least only

easily expressible recursively) this is true tree and graph operations, and search problems

that require backtracking The Cost/disadvantages:

recursive solutions are often harder to debug (need good IDE debugger tool)

recursion requires numerous function calling this can lead to much poorer run-time performance

takes up more memory space (on the run-time stack) in a few cases, solution may be much less efficient than an

iterative solution

A Recursive: Examples of usage Factorial:

fact(n): if(n < 2) 1 else n * fact(n – 1) Fibonacci:

fib(n): if (n < 3) 1 else fib(n – 1) + fib(n – 2) Finding largest item in an array:

largest(a, n): if (n = = 0) return a[0] else return max(a[n], largest(a, n-1))

We can also find the largest using a binary search like strategy: largest(a, low, high):

if(low = = high) return a[low] else return max(largest(a, low, (low+high)/2)), largest(a,

(low+high)/2+1, high)) Writing elements backwards

output_backward(S, n): if(n>=0) output_backwards(S, n-1) output character in S at position (n)

Chapter 9: Recursion 8

int factorial (int n){ if (!n) return 1; return n * factorial(n-1);}

SAME WITH

int factorial2 (int n) { int i, fact = 1; for (i = 1; i <= n; i++) { fact *= i; } return fact;}

Program code

Chapter 9: Recursion 9

#include <stdio.h>#include <stdlib.h>

int largestBinarySearch(int a[], int low, int high);int largest(int a[], int n);void backwards(char[], int n);

int factorial(int n) { if (n < 2) return 1; else return n * factorial(n - 1);}

int main() { printf("Factorial 5 is %d\n", factorial(5)); printf("Fibonacci 10 is %d\n", fibonacci(10)); int array[5] = {3, 2, 1, 5, 4}; printf("The largest item in the array is %d\n", largest(array, 4)); printf("The largest item in the array is %d\n", largestBinarySearch(array, 0, 4)); char string[7] = "UNITEN"; backwards(string, 5); return (EXIT_SUCCESS);}

Program code

Chapter 9: Recursion 10

int fibonacci(int n) { if (n < 3) return 1; return fibonacci(n - 1) + fibonacci(n - 2);}

int max(int x, int y) { return (x > y) ? x : y;}

int largest(int a[], int n) { if (n == 0) return a[0]; else return max(a[n], largest(a, n - 1));}

Program code

Chapter 9: Recursion 11

int largestBinarySearch(int a[], int low, int high) { if (low == high) return a[low]; else return max(largestBinarySearch(a, low, (low + high) / 2), largestBinarySearch(a, (low + high) / 2 + 1, high));}

void backwards(char S[], int n) { if (n > 0) backwards(S, n-1); printf("%c", S[n]);}

Chapter 9: Recursion 12

Comparison: Iterative Functions As mentioned earlier, we can use a recursion

technique as an alternative to the iteration technique.

Assume we want to calculate the summation of 1 + 2 + 3 + 4 + 5.

We can use iteration techniqueiteration technique to accomplish this taskint cal (int n)

{int j=1;

while ( j < n) {sum = sum + j;j++;

} }

Chapter 9: Recursion 13

Comparison: Recursive Functions Alternatively, we can use recursion technique recursion technique

to solve the problem.

int cal( int n){

if (n == 1 )return 1;

elsereturn ( n + cal(n-1));

}

Comparison: Recursive Functions (con’t)

Chapter 9: Recursion 14

N=4 => 4 + 3 + 2 + 1 = 10 “return ( n + cal(n-1))”

4

4 + cal (3)

3 + cal (2)

2 + cal (1)

1

4

4 + cal (3)

3 + cal (2)

2 + cal (1)

1

a) Sequence of recursive calls

1 returned

2 + 1 = 3 is returned

3 + 3 = 6 is returned

4 + 6 = 10 is returned

Final value = 10 is returned

b) Value returned from each recursive call (backtracking)

Chapter 9: Recursion 15

A Recursive: Simple example1

#include <stdio.h>void print_integers(int);

int main( ) {int number;printf(“Enter an integer: “);scanf(“%d”, number);print_integers(number);

}

void print_integers(int n) {

if (n>=1) {printf(“%d\n”, n);print_integers(n-1);

}}

Chapter 9: Recursion 16

A Recursive: Simple example1 (con’t) The function print_integers also has a

function call in its body to itself. The parameter in the statement

print_integers(n-1); is 1 less than n, the value in the previous call.

In other words, the problem that the function is expected to solve is smaller or simpler version of the previous problem.

Thus we can say that the problem size is gradually diminishing.

Chapter 9: Recursion 17

A Recursive: Simple example2

It is important to understand how a recursive function works. Assuming you have a factorial function as below

int Fact ( int n) {

if ( n == 1)return 1; i

elsereturn (n * Fact ( n-1)); ii

}

Chapter 9: Recursion 18

You can find the value of factorial 4 by calling Fact(4), but how does this function works and produce the output of Fact(4).

Fact(4) = ( 4 * Fact(3))= ( 4 * (3 * Fact(2)))= (4 * ( 3 * (2 * Fact(1))))= (4 * (3 * ( 2 * 1)))= (4 * (3 * (2)))= (4 * (6))= 24

A Recursive: Simple example2 (con’t)

Chapter 9: Recursion 19

Using graphical representation, this process can be illustrated as below

Fact (4)

Fact (4)iii 4 * Fact (3)

Fact 3iii. 3 * Fact (2)

Fact 2iii. 2 * Fact (1)

Fact 2iii. 2 * 1

Fact 3iii. 3 * 2

Fact 1i return 1ii

Fact 4iii 4 * 6

Tracing a Recursion Function

Chapter 9: Recursion 20

A Recursive: Simple example3

Assuming we want to develop a recursive solution to calculate the value of Xn . Firstly, we may need to study the formal notation solution of this problem. We can write the solution of Xn as below

X0 = 1…………………(i) base case statement

Xn = X . Xn-1…………(ii) recursive statement Statement (i) will serve as our base case

statement and the statement (ii) will serve as the recursive statement.

Chapter 9: Recursion 21

A Recursive: Simple example3 (con’t) So by having the definition, we can develop the

recursive function as below.

int pow ( int X, int n) {if ( n == 0)

return 1;else

return (X * pow ( X,n-1)); }

A Recursive: Simple example3 (con’t)

Exercise: Trace example3 using a graphical

representation as discussed in slide no. 18. The initial value of variable X=2 and n=3 What is the final output returned.

Chapter 9: Recursion 22

Chapter 9: Recursion 23

Example 4: Fibonacci numbers – Iteration technique

int fibonacci(int seq_num) {int first = 0, second = 1, count = 3, fibo;if(seq_num == 0)

fibo = first;else if(seq_num == 1)

fibo = second;else

while(count <= seq_num) { fibo = first + second; first = second; second = fibo; count++;}

return fibo;}

Fibonacci - a series of numbers created by adding the last two numbers in the series to produce the next number in the series, i.e., 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc.

Chapter 9: Recursion 24

Example 4: Fibonacci numbers - Recursive technique

int fibonacci(int seq_num) {if(seq_num == 0)

return 0;else if(seq_num == 1)

return 1;else

return fibonacci(seq_num -1) + fibonacci(seq_num -2);

}

This has simplified the iteration technique in the previous slide

25

(fib 5) (fib 3) (fib 4)

(fib 1) (fib 2) (fib 2) (fib 3)

(fib 0) (fib 1) (fib0)(fib 1) (fib 1) (fib 2)

(fib 0)(fib 1)

Tree of sub problems: Fibonacci

Chapter 9: Recursion

Chapter 9: Recursion 26

SUMMARY This chapter has introduced you;

How to construct simple recursion How recursion can simplify the iteration

technique in certain cases A few examples on recursion

Fibonacci Factorial Power of