Recursion and Function Implementation CS-2301 D-term 20091 Recursion and Implementation of Functions CS-2301 System Programming C-term 2009 (Slides include.

Slides:



Advertisements
Similar presentations
The University of Adelaide, School of Computer Science
Advertisements

CSI 3120, Implementing subprograms, page 1 Implementing subprograms The environment in block-structured languages The structure of the activation stack.
Procedures in more detail. CMPE12cGabriel Hugh Elkaim 2 Why use procedures? –Code reuse –More readable code –Less code Microprocessors (and assembly languages)
CPS3340 COMPUTER ARCHITECTURE Fall Semester, /17/2013 Lecture 12: Procedures Instructor: Ashraf Yaseen DEPARTMENT OF MATH & COMPUTER SCIENCE CENTRAL.
Prof. Necula CS 164 Lecture 141 Run-time Environments Lecture 8.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Introduction to Operating Systems CS-2301 B-term Introduction to Operating Systems CS-2301, System Programming for Non-majors (Slides include materials.
Arrays in CCS-2301, B-Term Arrays in C (including a brief introduction to pointers) CS-2301, System Programming for Non-Majors (Slides include materials.
Stacks and HeapsCS-3013 A-term A Short Digression on Stacks and Heaps CS-3013 Operating Systems A-term 2008 (Slides include materials from Modern.
1 Storage Registers vs. memory Access to registers is much faster than access to memory Goal: store as much data as possible in registers Limitations/considerations:
Procedures in more detail. CMPE12cCyrus Bazeghi 2 Procedures Why use procedures? Reuse of code More readable Less code Microprocessors (and assembly languages)
Digression on Stack and Heaps CS-502 (EMC) Fall A Short Digression on Stacks and Heaps CS-502, Operating Systems Fall 2009 (EMC) (Slides include.
CS 536 Spring Run-time organization Lecture 19.
3/17/2008Prof. Hilfinger CS 164 Lecture 231 Run-time organization Lecture 23.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
CS 3013 & CS 502 Summer 2006 Digressions:– Producer-Consumer and Stacks 1 Two Digressions Stacks Producer-Consumer models.
Arrays in CCS-2301 B-term Arrays in C (with a brief Introduction to Pointers) CS-2301, System Programming for Non-majors (Slides include materials.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Run time vs. Compile time
More on FunctionsCS-2301 B-term More on Functions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming Language,
Semantics of Calls and Returns
Process in Unix, Linux and Windows CS-3013 C-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
Scope Rules and Storage Types CS-2303, C-Term Scope Rules and Storage Types CS-2303, System Programming Concepts (Slides include materials from The.
Run-time Environment and Program Organization
Conditionals, Loops, and Other Statements CS-2301 D-term Conditionals, Loops, and Other Kinds of Statements CS-2301 System Programming C-term 2009.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
Processes in Unix, Linux, and Windows CS-502 Fall Processes in Unix, Linux, and Windows CS502 Operating Systems (Slides include materials from Operating.
Recursion and Implementation of Functions
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
CS-2710 Dr. Mark L. Hornick 1 Defining and calling procedures (subroutines) in assembly And using the Stack.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Runtime Environments Compiler Construction Chapter 7.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Compiler Construction
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Procedure Basics Computer Organization I 1 October 2009 © McQuain, Feng & Ribbens Procedure Support From previous study of high-level languages,
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Arrays in CCIS 1057 Fall Arrays in C (with a brief Introduction to Pointers) CIS 1057 Computer Programming in C Fall 2013 (Slides include materials.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
RecursionCIS 1057 Fall Recursion CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed from Professor Hugh C. Lauer. Slides.
A First Book of ANSI C Fourth Edition
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Storage Allocation Mechanisms
Storage Classes There are three places in memory where data may be placed: In Data section declared with .data in assembly language in C - Static) On the.
© Craig Zilles (adapted from slides by Howard Huang)
ENERGY 211 / CME 211 Lecture 25 November 17, 2008.
Run-time organization
Outline for this evening
Fundamentals of Programming
Recursion Data Structures.
The University of Adelaide, School of Computer Science
Recursion and Implementation of Functions
Scope Rules and Storage Types
UNIT V Run Time Environments.
CSC 143 Recursion.
Where is all the knowledge we lost with information? T. S. Eliot
© Craig Zilles (adapted from slides by Howard Huang)
Topic 2b ISA Support for High-Level Languages
Presentation transcript:

Recursion and Function Implementation CS-2301 D-term Recursion and Implementation of Functions CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel)

Recursion and Function Implementation CS-2301 D-term Definition Recursive Function:– a function that calls itself Directly or indirectly Each recursive call is made with a new, independent set of arguments Previous calls are suspended Allows very simple programs for very complex problems

Recursion and Function Implementation CS-2301 D-term Simplest Example int factorial(int x) { if (x <= 1) return 1; else return x * factorial (x-1); }// factorial

Recursion and Function Implementation CS-2301 D-term Simplest Example (continued) int factorial(int x) { if (x <= 1) return 1; else return x * factorial (x-1); }// factorial This puts the current execution of factorial “on hold” and starts a new one With a new argument!

Recursion and Function Implementation CS-2301 D-term Simplest Example (continued) int factorial(int x) { if (x <= 1) return 1; else return x * factorial (x-1); }// factorial When factorial(x-1 ) returns, its result it multiplied by x Mathematically:– x! = x  (x-1)!

Recursion and Function Implementation CS-2301 D-term Recursion (continued) There is an obvious circularity here –factorial calls factorial calls factorial, etc. But each one is called with a smaller value for argument! –Eventually, argument becomes ≤ 1 –Invokes if clause to terminate recursion

Recursion and Function Implementation CS-2301 D-term Simplest Example int factorial(int x) { if (x <= 1) return 1; else return x * factorial (x-1); }// factorial This if statement “breaks” the recursion

Recursion and Function Implementation CS-2301 D-term Questions?

Recursion and Function Implementation CS-2301 D-term More Interesting Example Towers of Hanoi Move stack of disks from one peg to another Move one disk at a time Larger disk may never be on top of smaller disk

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0) { move (disks-1, a, c, b); printf ("Move one disk from %d to %d\n", a, c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk from %d to %d\n", a, c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move The function main – gets number of disks and invokes function move

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move The function move – where the action is

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move First move all but one of the disks to temporary peg

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move Next, move the remaining disk to the destination peg

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move Finally, move disks from temporary to destination peg

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move Notice that move calls itself twice, but with one fewer disks each time

Recursion and Function Implementation CS-2301 D-term Why Recursion? Not often used by programmers with ordinary skills in some areas, but … … some problems are too hard to solve without recursion –Most notably, the compiler! –Tower of Hanoi problem –Most problems involving linked lists and trees (Later in the course)

Recursion and Function Implementation CS-2301 D-term Recursion vs. Iteration Some simple recursive problems can be “unwound” into loops But code becomes less compact, harder to follow! Hard problems cannot easily be expressed in non-recursive code Tower of Hanoi Robots or avatars that “learn” Advanced games

Recursion and Function Implementation CS-2301 D-term Recursion is so important … … that all modern computer architectures specifically support it Stack register Instructions for manipulating The Stack … most modern programming languages allow it But not Fortran and not Cobol

Recursion and Function Implementation CS-2301 D-term Personal Observation From my own experience, programming languages and environments that do not support recursion … … are usually not rich enough to support a diverse portfolio of programs I.e., a wide variety of applications in many different disciplines

Recursion and Function Implementation CS-2301 D-term Questions?

Recursion and Function Implementation CS-2301 D-term Data Storage in Memory Variables may be automatic or static Automatic variables may only be declared within functions and compound statements (blocks) Storage allocated when function or block is entered Storage is released when function returns or block exits Parameters and result are (somewhat) like automatic variables Storage is allocated and initialized by caller of function Storage is released after function returns to caller.

Recursion and Function Implementation CS-2301 D-term Static variables may be declared within or outside of functions Storage allocated when program is initialized Storage is released when program exits Static variables outside of functions may be visible to linker Compiler sets aside storage for all static variables at compiler or link time Values retained across function calls Initialization must evaluate to compile-time constant Static Data

Recursion and Function Implementation CS-2301 D-term Static Variable Examples int j;//static, visible to linker & all functs static float f; // not visible to linker, visible to // to all functions in this program int fcn (float a, int b) { // nothing inside of {} is visible to linker int i = b;//automatic double g;//automatic static double h;//static, not visible to // linker; value retained from call to call body – may access j, f, a, b, i, g, h }//int fcn( … )

Recursion and Function Implementation CS-2301 D-term Static Variable Examples (continued) int j;//static, visible to linker & all functs static float f; // not visible to linker, visible to // to all functions in this program int fcn (float a, int b) { // nothing inside of {} is visible to linker int i = b;//automatic double g;//automatic static double h;//static, not visible to // linker; value retained from call to call body – may access j, f, a, b, i, g, h }//int fcn( … ) Declaration outside any function:– always static static storage class:– not visible to linker

Recursion and Function Implementation CS-2301 D-term Static Variable Examples (continued) int j;//static, visible to linker & all functs static float f; // not visible to linker, visible to // to all functions in this program int fcn (float a, int b) { // nothing inside of {} is visible to linker int i = b;//automatic double g;//automatic static double h;//static, not visible to // linker; value retained from call to call body – may access j, f, a, b, i, g, h }//int fcn( … ) Inside function:– default is automatic static storage class:– not visible to linker

Recursion and Function Implementation CS-2301 D-term Static Variable Examples (continued) int j;//static, visible to linker & all functs static float f; // not visible to linker, visible to // to all functions in this program int fcn (float a, int b) { // nothing inside of {} is visible to linker int i = b;//automatic double g;//automatic static double h;//static, not visible to // linker; value retained from call to call body – may access j, f, a, b, i, g, h }//int fcn( … ) Note: value of h is retained from one call to next Value of h is also retained across recursions

Recursion and Function Implementation CS-2301 D-term Extern Variables int j;//static, visible to linker & all functs static float f; // not visible to linker, visible to // to all functions in this program extern float p; // static, defined in another program int fcn (float a, int b) { // nothing inside of {} is visible to linker int i = b;//automatic double g;//automatic static double h;//static, not visible to // linker; value retained from call to call body – may access j, f, a, b, i, g, h, p }//int fcn( … ) extern storage class:– a static variable defined in another C program

Recursion and Function Implementation CS-2301 D-term Questions?

Recursion and Function Implementation CS-2301 D-term Automatic Variables, Arguments, & Results Allocated on The Stack Definition – The Stack –A last-in, first-out data structure provided by the operating system for each running program –For temporary storage of automatic variables, arguments, function results, and other stuff Used by all modern programming languages –Even assembly languages for modern processors –… but not Fortran or Cobol!

Recursion and Function Implementation CS-2301 D-term Automatic Variables Allocated when function or compound statement is entered Released when function or compound statement is exited Values not retained from execution to next

Recursion and Function Implementation CS-2301 D-term Arguments and Results Arguments are values calculated by caller of function Placed on The Stack by caller for use by function Function may assign new value to argument, but … …caller never looks at argument values again! Result is storage allocated by caller On The Stack Assigned by return statement of function For use by caller Arguments & result are removed by caller After function returns, after caller has absorbed return value

Recursion and Function Implementation CS-2301 D-term Typical Implementation of The Stack Linear region of memory Stack Pointer “growing” downward Each time some information is pushed onto The Stack, pointer moves downward Each time info is popped off of The Stack, pointer moves back upward

Recursion and Function Implementation CS-2301 D-term Typical Memory for Running Program (Windows & Linux) 0x xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP

Recursion and Function Implementation CS-2301 D-term Typical Memory for Running Program (Windows & Linux) 0x xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP Heap to be discussed later in course

Recursion and Function Implementation CS-2301 D-term How it works Imagine the following program:– int factorial(int n){ … /* body of factorial function */ … }// factorial Imagine also the caller:– int x = factorial(100); What does compiled code look like?

Recursion and Function Implementation CS-2301 D-term Compiled code: the caller int x = factorial(100); Put the value “100” somewhere that factorial function can find Put the current program counter somewhere so that factorial function can return to the right place in calling function Provide a place to put the result, so that calling function can find it

Recursion and Function Implementation CS-2301 D-term Compiled code: factorial function Save the caller’s registers somewhere Get the argument n from the agreed-upon place Set aside some memory for local variables and intermediate results Do whatever factorial was programmed to do Put the result where the caller can find it Restore the caller’s registers Transfer back to the program counter saved by the caller

Recursion and Function Implementation CS-2301 D-term Question: Where is “somewhere”? So that caller can provide as many arguments as needed (within reason)? So that called routine can decide at run-time how much temporary space is needed? So that called routine can call any other routine, potentially recursively?

Recursion and Function Implementation CS-2301 D-term Answer: The Stack Calling function Push space for result, and arguments onto stack Push return address and Jump to called function Called function Push registers and automatic storage space onto stack Do work of the routine, store result in space pushed above Pop registers and automatic storage off stack Jump to return address left by calling routine

Recursion and Function Implementation CS-2301 D-term Typical Address Space (Windows & Linux) 0x xFFFFFFFF Memory address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP

Recursion and Function Implementation CS-2301 D-term Note Through the magic of operating systems, each running program has its own memory –Complete with stack & everything else Called a process Windows, Linux, Unix, etc.

Recursion and Function Implementation CS-2301 D-term Note (continued) Not necessarily true in small, embedded systems Real-time & control systems Mobile phone & PDA Remote sensors, instrumentation, etc. Multiple running programs share a memory Each in own partition with own stack Barriers to prevent each from corrupting others

Recursion and Function Implementation CS-2301 D-term Shared Physical Memory OS Kernel stack Process 1 stack Process 2 0x x0000FFFF Physical memory stack Process 3

Recursion and Function Implementation CS-2301 D-term Questions?

Recursion and Function Implementation CS-2301 D-term Why a Stack? Engineering reason – Computer architectures without stacks are not “rich” enough to support demands of modern computing Multiple running programs at the same time Complex interactions among running programs Modern computer languages Mathematical reason – To support recursive programs Not often used by programmers with ordinary skills, but … Some problems are too hard to solve without recursion Most notably, the compiler!

Recursion and Function Implementation CS-2301 D-term Why a Stack? Engineering reason – Computer architectures without stacks are not “rich” enough to support demands of modern computing Multiple running programs at the same time Complex interactions among running programs Modern computer languages Mathematical reason – To support recursive programs Not often used by programmers with ordinary skills, but … Some problems are too hard to solve without it Also, advanced games and robotics with “intelligent” objects

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program & Use of Stack #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack n SP Stack entry for main …

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 1 c = 2 b = 3 disks = n-1 Args for 2 nd call to move

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 1 c = 2 b = 3 disks = n-1 Args for 2 nd call to move Args for subsequent calls to move go here

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 1 c = 2 b = 3 disks = n-1 Args for 2 nd call to move Eventually, disks = 0, so no more calls to move All existing calls return

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move Leaving stack like this again

Recursion and Function Implementation CS-2301 D-term Tower of Hanoi Program #include void move (int disks, int a, int c, int b); int main() { int n; printf ("How many disks?"); scanf ("%d", &n); printf ("\n"); move (n, 1, 3, 2); return 0; }// main /* PRE: n >= 0; a, b, and c represent some order of the distinct integers 1, 2, 3 POST: the function displays the individual moves necessary to move n disks from needle a to needle c, using needle b as a temporary storage needle */ void move (int disks, int a, int c, int b) { if (disks > 0){ move (disks-1, a, c, b); printf ("Move one disk " "from %d to %d\n",a,c); move (disks-1, b, a, c); }// if (disks > 0 return; }//move

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move move now moves one disk from peg1 to peg3, and then calls move again!

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 3 c = 2 b = 1 disks = n-1 Args for call to move disks back from peg3 to peg2

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 3 c = 2 b = 1 disks = n-1 Args for call to move back Args for subsequent calls to move back go here

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move return address a = 3 c = 2 b = 1 disks = n-1 Args for 2 nd call to move Eventually, disks = 0, so no more calls to move All existing calls return

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack (continued) n SP Stack entry for main … return address a = 1 c = 3 b = 2 disks = n Args for call to move Leaving stack like this again, but with all disks moved to peg 3

Recursion and Function Implementation CS-2301 D-term Implementation on The Stack n SP Stack entry for main … move returns back to main

Recursion and Function Implementation CS-2301 D-term Fundamental Principle Stack provides a simple mechanism for implementing recursive functions Arbitrary numbers of intermediate functions Eventually, something must break the circularity of recursion Or stack will grow until it overflows memory!

Recursion and Function Implementation CS-2301 D-term Note on Recursive Functions Some simple recursive functions can be “unwound” into loops – e.g., int factorial(int n) { return (n <= 1) ? 1 : (n * factorial(n-1)); }//factorial is equivalent to int factorial(int n) { int product = 1; for (int k=1; k <= n; k++) product *= k; return product } //factorial

Recursion and Function Implementation CS-2301 D-term Note on Recursive Functions (continued) Other recursive functions are much too difficult to understand if unwound E.g., Tower of Hanoi Keeping track of which disk is on which peg requires superhuman intellect, very complex code!

Recursion and Function Implementation CS-2301 D-term Questions?