Lect11_Functions_III - ICS103 Programming in C Lecture 11 Recursive Functions 1 Outline Recursive functions and Recursion Writing a recursive function

# Lect11_Functions_III - ICS103 Programming in C Lecture 11...

This preview shows page 1 - 7 out of 20 pages.

1 ICS103 Programming in C Lecture 11: Recursive Functions Outline Recursive functions and Recursion Writing a recursive function Recursion vs Repetition Tracing Recursive Functions Examples Mutually recursive functions Common errors 2 What is a recursive function? A recursive function is a function that calls itself either directly or indirectly In C, any function can call itself Example: What is the output of the following program? 3 #include <stdio.h> main() { printf(" Going around! "); main() ; } Why recursive functions? Recursion is a powerful problem solving technique Many mathematical functions can be defined recursively Example: Factorial Function 5! = 5 * 4 * 3 * 2 * 1 or 5! = 5 * 4! 0! = 1 in general By re-appling the recursive case(s), solution will move closer and eventually reach the base case(s) 4 1 n = 0 n (n-1)! n > 0 n! = base case recursive case Writing a recursive function Recursive functions generally involve an if statement The if-branch is the base case, while the else-branch is the recursive case. The recursive case provides the repetition needed for the solution and the base case provides the termination. For the recursion to terminate, each recursive call must be moving closer to a base case. if this is a base case solve it else redefine the problem using recursion 5 Recursion vs Repetition Recursive version int factorial (int n){ if (n == 0) return 1; else return n * factorial (n- 1); } Iterative version int factorial (int n){ int i, product=1; for (i=n; i>1; --i) product=product * i; return product; } 6 Computing the factorial of a number n  #### You've reached the end of your free preview.

Want to read all 20 pages?

• Summer '14
• Darwish
• Recursion, scanf, recursive functions
• • •  