


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to recursion in computer science, covering the concepts of factorials, integer exponentiation, recursive c++ functions, and binary search. It includes examples and exercises for students to practice.
Typology: Study notes
1 / 4
This page cannot be seen from the preview
Don't miss anything!



We will look at more sophisticated problems in Lecture 10.
n! =
n · (n − 1)! n > 0 1 n == 0
np^ =
n · np−^1 p > 0 1 p == 0
C++, like other modern programming languages, allows functions to call themselves. This gives a direct method of implementing recursive functions.
int fact(int n) { if (n == 0) { return 1; } else { int result = fact(n-1); return n * result; } }
int intpow(int n, int p) { if (p == 0) { return 1; } else { return n * intpow( n, p-1 ); } }
1
fact(4) n= result = fact(3) return 4*
fact(3) n= result = fact(2) return 3*
fact(2) n= result = fact(1) return 2*
fact(1) n= result = fact(0) return 1*
fact(0) n= return 1
2
1
24
6
int ifact(int n) { int result = 1; for (int i=1; i<=n; ++i) result = result * i; return result; }
int main() { vector
v[0] <= v[1] <= v[2] <= ...
template