110 likes | 225 Views
This lecture introduces recursion, a fundamental concept in programming. We explore how functions can call themselves to solve problems, focusing on calculating factorials and powers. The recursive definition of the factorial function demonstrates its structure and logic, while the power function illustrates a similar recursive approach. Key rules for using recursion include identifying base and terminal cases, and ensuring that each recursive call progresses toward a solution. The mechanics of function calls are also discussed, emphasizing the role of the system stack.
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