# Recursion - Recursion Recursion is a function invoking...

This preview shows pages 1–6. Sign up to view the full content.

Recursion Recursion is a function invoking itself, either directly or indirectly. It can be used as an alternative to iteration. Recursion is an important and powerful tool in problem solving and programming. It is a programming technique that naturally implements the divide-and-conquer problem solving methodology. In its simplest form the idea of recursion is straightforward: Example 1: void count_down(int n) { if (n <= 0) printf(“\nBlast off.\n”); else{ printf(“%d! “, n); count_down(n-1); } } int main () { count_down(10); } 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Example 2: Multiplication of natural numbers. a * b = a added to itself b times. (iterative definition) a * b = a if b=1 (recursive definition) a* b = a * (b-1) + a if b > 1 e.g. 6 * 3 = 6 * 2 + 6 = 6 * 1 + 6 + 6 = 6 + 6 + 6 = 18 In C: int multiply(int a, int b) { if (b == 1) /* stopping case */ return a; else /* recursive step */ return ( a + multiply(a, b-1)); } 2
Example 3: Factorial Function n! = n * (n-1) * (n-2) * … * 2 * 1 5! = 5 * 4 * 3* 2 * 1 0! = 1 Mathematical definition: n! = 1 if n = 0 n! = n . (n-1) . (n-2). … . 2 . 1 if n > 0 Iteratively: p = 1; for (x=n; x>=1; x--) p = p* x; Recursive definition: 4! = 4 * 3 * 2 * 1 = 4 * 3! n! = n * (n-1)! 3

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Thus, n! = 1 if n = 0 n! = n*(n-1)! if n > 0 In C: int factorial(int n) { if (n ==0) return 1; else return (n * factorial(n-1)); } 4
The Nature of Recursion 1) One or more simple cases of the problem (called the stopping cases ) have a simple non-recursive solution. 2) The other cases of the problem can be reduced ( using recursion ) to problems that are closer to stopping cases. 3)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This document was uploaded on 06/12/2011.

### Page1 / 19

Recursion - Recursion Recursion is a function invoking...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online