110 likes | 217 Views
IS12 - Introduction to Programming Lecture 23: Recursion. Peter Brusilovsky http://www2.sis.pitt.edu/~peterb/0012-051/. Recursive Definitions. Factorial function can be defined recursively (function definition use this function as a part of definition). Recursive Calculations.
E N D
IS12 - Introduction to Programming Lecture 23: Recursion Peter Brusilovsky http://www2.sis.pitt.edu/~peterb/0012-051/
Recursive Definitions • Factorial function can be defined recursively (function definition use this function as a part of definition)
Recursive Calculations • Recursive definition can be used to calculate factorial
Recursive factorial voidmain(){ int i; printf("Enter an integer (non-negative): "); scanf("%d", &i); if(i >= 0) printf("%d! = %d\n", i, factorial(i)); } int factorial(int n) { if(n == 0) return 1; else return (n * factorial(n-1)); }
Rules for Using Recursion • Every recursive call must either solve the problem or reduce its size • Terminal case: solving (no calls) • Base case: reducing size (recursive call) • To make a recursive program: • Identify base case(s) and terminal case(s) • Combine them (usually with if-else)
Recursive Power voidmain(){ int a, b; printf("Enter a and b: "); scanf("%d %d", &a, &b); if(b >= 0) printf("%d power %d = %d\n", a, b, power(a, b)); } int power(int base, int exp) { if(exp == 0) return 1; else return (base * power(base, exp-1)); }
Stackframe and system stack • When one function calls another function in C all parameters and return value are transferred via system stack • At each call a stackframe is placed into stack • Parameters of the call • Local variable of calling function • Next statement in the calling function • Place for a return value
The process of calling a function • Calling function: pushes stackframe • Called function: • Gets parameters from the stack • Performs calculations • Places return value to the stack • Transfers control to the next statement • Calling function • Restores local variables from the stack • Uses return value from the stack