Professional Documents
Culture Documents
Functions
CS-2303
System Programming Concepts
(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)
Definition
Recursive Function: a function that calls
itself
Directly or indirectly
Simplest Example
int factorial(int x) {
if (x <= 1)
return 1;
else
return x * factorial (x-1);
} // factorial
//
move
5
And here?
return;
} //
move
CS-2303, C-Term 2010
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)
CS-2303, C-Term 2010
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
10
Questions?
11
12
13
Recursion is so important
that all modern computer architectures
specifically support it
Stack register
Instructions for manipulating The Stack
14
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)
CS-2303, C-Term 2010
15
On The Stack
Assigned by return statement of function
For use by caller
16
17
stack
(dynamically allocated)
SP
address space
heap
(dynamically allocated)
static data
0x00000000
program code
(text)
PC
18
stack
(dynamically allocated)
SP
address space
heap
(dynamically allocated)
static data
0x00000000
program code
(text)
He
ap
in c to be
our disc
se
u ss
e
PC
19
d la
ter
How it works
Imagine the following program:
int factorial(int n){
}
// factorial
20
21
22
stack
(dynamically allocated)
SP
Memory
address space
heap
(dynamically allocated)
static data
0x00000000
program code
(text)
PC
23
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.
CS-2303, C-Term 2010
24
Note (continued)
Not necessarily true in small, embedded
systems
Real-time & control systems
Mobile phone & PDA
Remote sensors, instrumentation, etc.
25
stack
Process 3
stack
Physical
Process 2
memory
stack
Process 1
OS Kernel
0x00000000
CS-2303, C-Term 2010
26
Questions?
27
28
29
Questions?
30