1 / 11

IS12 - Introduction to Programming Lecture 23: Recursion

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.

gage-barnes
Download Presentation

IS12 - Introduction to Programming Lecture 23: Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IS12 - Introduction to Programming Lecture 23: Recursion Peter Brusilovsky http://www2.sis.pitt.edu/~peterb/0012-051/

  2. Recursive Definitions • Factorial function can be defined recursively (function definition use this function as a part of definition)

  3. Recursive Calculations • Recursive definition can be used to calculate factorial

  4. 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)); }

  5. 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)

  6. 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)); }

  7. How it works? Power Case

  8. 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

  9. 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

More Related