Lecture221 recursion

# Lecture221 recursion - Recursion A recursive function must...

This preview shows pages 1–4. Sign up to view the full content.

Lecture 1 -- 1 Computer Science I - Martin Hardwick Recursion A recursive function must have at least two parts A part that solves a simple case of the problem without  recursion A part that makes the problem simpler and then uses recursion Here is a simple recursive function int factorial (int val) { cout << “Entering with val = “ << val << endl; if (val == 1) { // simple part cout << “Simple case” << endl; return 1; { else { // simplification part int n = val * factorial (val-1); cout << “Leaving n = “ << n << endl; return (n); } }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Lecture 1 -- 2 Computer Science I - Martin Hardwick Factorial 5 As we enter the function we print the current val When we get to the simple case we print “Simple case” As we exit we print the value of n
Lecture 1 -- 3 Computer Science I - Martin Hardwick The call stack As each function is entered a frame is added to the call stack The frame contains the values of the local variables The frame is created for both recursive and non-recursive functions CALL Stack: f3 () F3: f2 () F2: call f1 () F1: call return return

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 03/30/2012 for the course CSCI 101 taught by Professor Hardwick during the Fall '08 term at Rensselaer Polytechnic Institute.

### Page1 / 9

Lecture221 recursion - Recursion A recursive function must...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online