Recursion and Function
Implementation
1
Recursion and Implementation of
Functions
(Slides include materials from The C Programming Language, 2nd
edition, by Kernighan and Ritchie and
from C: How to Program, 5th
and 6th
editions, by Deitel and Deitel)
Recursion and Function
Implementation
2
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
3
Simplest Example
int factorial(int x) {
if (x <= 1)
return 1;
else
return x * factorial (x-1);
} // factorial
Recursion and Function
Implementation
4
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
5
Tower of Hanoi Program
#include <stdio.h>
void move (int n, int a, int c, int b);
int main() {
int disks;
printf ("How many disks?");
scanf ("%d", &disks);
move (disks, 1, 3, 2);
return 0;
} // main
/* PRE: n >= 0. Disks are arranged
small to large on the pegs a, b,
and c. At least n disks on peg
a. No disk on b or c is smaller
than the top n disks of a.
POST: The n disks have been moved
from a to c. Small to large
order is preserved. Other disks
on a, b, c are undisturbed. */
void move (int n, int a, int c, int
b) {
if (n > 0)
{
move (n-1, a, b, c);
printf ("Move one disk
from %d to %dn", a, c);
move (n-1, b, c, a);
} // if (n > 0)
return;
} // move
• Is pre-condition satisfied before
this call to move?
Recursion and Function
Implementation
6
Tower of Hanoi Program
#include <stdio.h>
void move (int n, int a, int c, int b);
int main() {
int disks;
printf ("How many disks?");
scanf ("%d", &disks);
move (disks, 1, 3, 2);
return 0;
} // main
/* PRE: n >= 0. Disks are arranged
small to large on the pegs a, b,
and c. At least n disks on peg
a. No disk on b or c is smaller
than the top n disks of a.
POST: The n disks have been moved
from a to c. Small to large
order is preserved. Other disks
on a, b, c are undisturbed. */
void move (int n, int a, int c, int
b) {
if (n > 0)
{
move (n-1, a, b, c);
printf ("Move one disk
from %d to %dn", a, c);
move (n-1, b, c, a);
} // if (n > 0)
return;
} // move
• If pre-condition is satisfied here, is it
still satisfied here?
And here?
Recursion and Function
Implementation
7
Tower of Hanoi Program
#include <stdio.h>
void move (int n, int a, int c, int b);
int main() {
int disks;
printf ("How many disks?");
scanf ("%d", &disks);
move (disks, 1, 3, 2);
return 0;
} // main
/* PRE: n >= 0. Disks are arranged
small to large on the pegs a, b,
and c. At least n disks on peg
a. No disk on b or c is smaller
than the top n disks of a.
POST: The n disks have been moved
from a to c. Small to large
order is preserved. Other disks
on a, b, c are undisturbed. */
void move (int n, int a, int c, int
b) {
if (n > 0)
{
move (n-1, a, b, c);
printf ("Move one disk
from %d to %dn", a, c);
move (n-1, b, c, a);
} // if (n > 0)
return;
} // move
If pre-condition is true and
if n = 1, does move satisfy
the post-condition?
Can we reason that this
program correctly plays
Tower of Hanoi?
Recursion and Function
Implementation
8
Why Recursion?
• Are article of faith among CS students and faculty
but …
• … a surprise to non-CS students.
• 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
9
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
10
Personal Observation
• From my own experience, programming
languages, environments, and computer
architectures that do not support recursion
• … are usually not rich enough to support a
diverse portfolio of applications
• I.e., a wide variety of problems in many different
disciplines
Recursion and Function
Implementation
11
Questions?
Recursion and Function
Implementation
12
Implementing Recursion — 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
• I.e., the working storage for each, separate
function call.
Recursion and Function
Implementation
13
The Stack (continued)
• Every single time a function is called, an
area of the stack is reserved for that
particular call.
• Known as its activation record in compiler
circles.
Recursion and Function
Implementation
14
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
15
Recursion in C
• Parameters, results, and automatic variables
allocated on the stack.
• Allocated when function or compound statement
is entered
• Released when function or compound statement is
exited
• Values are not retained from one call to next (or
among recursions)
Recursion and Function
Implementation
16
Arguments and Results
1. Space for storing result is allocated by caller
• On The Stack
• Assigned by return statement of function
• For use by caller
2. Arguments are values calculated by caller of
function
• Placed on The Stack by caller in locations set aside for the
corresponding parameters
• Function may assign new value to parameter, but …
• …caller never looks at parameter/argument values again!
3. Arguments are removed when callee returns
• Leaving only the result value for the caller
Recursion and Function
Implementation
17
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
18
Typical Memory for Running Program
(Windows & Linux)
0x00000000
0xFFFFFFFF
address space
program code
(text)
static data
heap
(dynamically allocated)
stack
(dynamically allocated)
PC
SP
Recursion and Function
Implementation
19
Typical Memory for Running Program
(Windows & Linux)
0x00000000
0xFFFFFFFF
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
20
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
21
Compiled code: the caller
int x = factorial(100);
• Provide integer-sized space on stack for result, so
that calling function can find it
• Evaluate the expression “100” and leave it on the
stack (after result)
• Put the current program counter somewhere so
that factorial function can return to the right place
in calling function
• Transfer control to the called function
Recursion and Function
Implementation
22
Compiled code: factorial function
• Save the caller’s registers in a dedicated space in
the activation record
• Get the parameter n from the stack
• Set aside some memory for local variables and
intermediate results on the stack
• Do whatever factorial was programmed to do
• Put the result in the space allocated by the caller
• Restore the caller’s registers
• Transfer back to the program counter saved by the
caller
Recursion and Function
Implementation
23
Typical Address Space (Windows & Linux)
0x00000000
0xFFFFFFFF
Memory
address space
program code
(text)
static data
heap
(dynamically allocated)
stack
(dynamically allocated)
PC
SP
Recursion and Function
Implementation
24
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
25
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
26
Shared Physical Memory
OS Kernel
stack
Process 1
stack
Process 2
0x00000000
0x0000FFFF
Physical
memory
stack
Process 3
Recursion and Function
Implementation
27
Questions?
Recursion and Function
Implementation
28
The Stack (summary)
• The stack gives each function call its own,
private place to work
• Separate from all other calls to same function
• Separate from all calls to other functions
• Place for automatic variables, parameters, results
Recursion and Function
Implementation
29
The Stack (continued)
• Originally intended to support recursion
• Mostly for computer scientists
• Compiler writers, etc.
• Powerful enabling concept
• Allows function to be shared among multiple
running programs
• Shared libraries
• Concurrent activities within a process
Recursion and Function
Implementation
30
Questions?

Recursion And Implementation C Programming

  • 1.
    Recursion and Function Implementation 1 Recursionand Implementation of Functions (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
  • 2.
    Recursion and Function Implementation 2 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
  • 3.
    Recursion and Function Implementation 3 SimplestExample int factorial(int x) { if (x <= 1) return 1; else return x * factorial (x-1); } // factorial
  • 4.
    Recursion and Function Implementation 4 MoreInteresting 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
  • 5.
    Recursion and Function Implementation 5 Towerof Hanoi Program #include <stdio.h> void move (int n, int a, int c, int b); int main() { int disks; printf ("How many disks?"); scanf ("%d", &disks); move (disks, 1, 3, 2); return 0; } // main /* PRE: n >= 0. Disks are arranged small to large on the pegs a, b, and c. At least n disks on peg a. No disk on b or c is smaller than the top n disks of a. POST: The n disks have been moved from a to c. Small to large order is preserved. Other disks on a, b, c are undisturbed. */ void move (int n, int a, int c, int b) { if (n > 0) { move (n-1, a, b, c); printf ("Move one disk from %d to %dn", a, c); move (n-1, b, c, a); } // if (n > 0) return; } // move • Is pre-condition satisfied before this call to move?
  • 6.
    Recursion and Function Implementation 6 Towerof Hanoi Program #include <stdio.h> void move (int n, int a, int c, int b); int main() { int disks; printf ("How many disks?"); scanf ("%d", &disks); move (disks, 1, 3, 2); return 0; } // main /* PRE: n >= 0. Disks are arranged small to large on the pegs a, b, and c. At least n disks on peg a. No disk on b or c is smaller than the top n disks of a. POST: The n disks have been moved from a to c. Small to large order is preserved. Other disks on a, b, c are undisturbed. */ void move (int n, int a, int c, int b) { if (n > 0) { move (n-1, a, b, c); printf ("Move one disk from %d to %dn", a, c); move (n-1, b, c, a); } // if (n > 0) return; } // move • If pre-condition is satisfied here, is it still satisfied here? And here?
  • 7.
    Recursion and Function Implementation 7 Towerof Hanoi Program #include <stdio.h> void move (int n, int a, int c, int b); int main() { int disks; printf ("How many disks?"); scanf ("%d", &disks); move (disks, 1, 3, 2); return 0; } // main /* PRE: n >= 0. Disks are arranged small to large on the pegs a, b, and c. At least n disks on peg a. No disk on b or c is smaller than the top n disks of a. POST: The n disks have been moved from a to c. Small to large order is preserved. Other disks on a, b, c are undisturbed. */ void move (int n, int a, int c, int b) { if (n > 0) { move (n-1, a, b, c); printf ("Move one disk from %d to %dn", a, c); move (n-1, b, c, a); } // if (n > 0) return; } // move If pre-condition is true and if n = 1, does move satisfy the post-condition? Can we reason that this program correctly plays Tower of Hanoi?
  • 8.
    Recursion and Function Implementation 8 WhyRecursion? • Are article of faith among CS students and faculty but … • … a surprise to non-CS students. • 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)
  • 9.
    Recursion and Function Implementation 9 Recursionvs. 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
  • 10.
    Recursion and Function Implementation 10 PersonalObservation • From my own experience, programming languages, environments, and computer architectures that do not support recursion • … are usually not rich enough to support a diverse portfolio of applications • I.e., a wide variety of problems in many different disciplines
  • 11.
  • 12.
    Recursion and Function Implementation 12 ImplementingRecursion — 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 • I.e., the working storage for each, separate function call.
  • 13.
    Recursion and Function Implementation 13 TheStack (continued) • Every single time a function is called, an area of the stack is reserved for that particular call. • Known as its activation record in compiler circles.
  • 14.
    Recursion and Function Implementation 14 Recursionis 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
  • 15.
    Recursion and Function Implementation 15 Recursionin C • Parameters, results, and automatic variables allocated on the stack. • Allocated when function or compound statement is entered • Released when function or compound statement is exited • Values are not retained from one call to next (or among recursions)
  • 16.
    Recursion and Function Implementation 16 Argumentsand Results 1. Space for storing result is allocated by caller • On The Stack • Assigned by return statement of function • For use by caller 2. Arguments are values calculated by caller of function • Placed on The Stack by caller in locations set aside for the corresponding parameters • Function may assign new value to parameter, but … • …caller never looks at parameter/argument values again! 3. Arguments are removed when callee returns • Leaving only the result value for the caller
  • 17.
    Recursion and Function Implementation 17 TypicalImplementation 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
  • 18.
    Recursion and Function Implementation 18 TypicalMemory for Running Program (Windows & Linux) 0x00000000 0xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP
  • 19.
    Recursion and Function Implementation 19 TypicalMemory for Running Program (Windows & Linux) 0x00000000 0xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP Heap to be discussed later in course
  • 20.
    Recursion and Function Implementation 20 Howit 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?
  • 21.
    Recursion and Function Implementation 21 Compiledcode: the caller int x = factorial(100); • Provide integer-sized space on stack for result, so that calling function can find it • Evaluate the expression “100” and leave it on the stack (after result) • Put the current program counter somewhere so that factorial function can return to the right place in calling function • Transfer control to the called function
  • 22.
    Recursion and Function Implementation 22 Compiledcode: factorial function • Save the caller’s registers in a dedicated space in the activation record • Get the parameter n from the stack • Set aside some memory for local variables and intermediate results on the stack • Do whatever factorial was programmed to do • Put the result in the space allocated by the caller • Restore the caller’s registers • Transfer back to the program counter saved by the caller
  • 23.
    Recursion and Function Implementation 23 TypicalAddress Space (Windows & Linux) 0x00000000 0xFFFFFFFF Memory address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP
  • 24.
    Recursion and Function Implementation 24 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.
  • 25.
    Recursion and Function Implementation 25 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
  • 26.
    Recursion and Function Implementation 26 SharedPhysical Memory OS Kernel stack Process 1 stack Process 2 0x00000000 0x0000FFFF Physical memory stack Process 3
  • 27.
  • 28.
    Recursion and Function Implementation 28 TheStack (summary) • The stack gives each function call its own, private place to work • Separate from all other calls to same function • Separate from all calls to other functions • Place for automatic variables, parameters, results
  • 29.
    Recursion and Function Implementation 29 TheStack (continued) • Originally intended to support recursion • Mostly for computer scientists • Compiler writers, etc. • Powerful enabling concept • Allows function to be shared among multiple running programs • Shared libraries • Concurrent activities within a process
  • 30.