Download presentation
Presentation is loading. Please wait.
Published byRoy Farmer Modified over 9 years ago
1
Chapter 15 Recursion
2
15.1 INTRODUCTION Recursion is a program-solving technique that expresses the solution of a problem in terms of the solutions of similar but smaller problems. Recursion is a powerful program-solving technique in computer science and mathematics. A recursive function is one that calls itself repetitively until a final call is made that no longer requires a self-call.
3
15.2 RECURSIVE PROBLEMS AND RECURSIVE FUNCTIONS Void print_integers (int n) { if (n > = 1) { printf (“%d\n”, n) ; print_integers (n-1) ; } /* end if */ } /* end function print_integers */ Figure 15.2 A function that calls itself recursively
4
A solution to a problem is recursive if it is expressible as a smaller version of itself and if ultimately a simple nonrecursive solution can be found A function that calls itself to solve a smaller version of its task until a final call that does not require a self–call is a recursive function.
5
15.3 A RECUSIVE VALUED FUNCTION THAT COMPUTES FACTORIALS fact (n) =1* 2 *……..* n Where n is a nonnegative integer fact(0) = 1
6
int fact(int num) { if (num==0) return 1 ; else return (num * fact (num-1); /* end if */ } /* end function fact */ Figure 15.4 A recursive C function that computes factorial
7
15.4 TRACING RECURSIVE VALUED FUNCTIONS The difficulty in recursion is keeping track of the incomplete recursive function calls. The operating system use a special data structure called a stack to do this. Figure 15.5 Manual trace of the recursive function call fact(4). A stack is a last-in-first-out list;the last element that is inserted into it is accessed,processed,and deleted from the list.
8
Figure 15.14 A recursive C implementation of the sequential search algorithm for an ordered list. Figure 15.16 A pseudocode algorithm for Recursive binary search.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.