Lecture-21-Recursion - Recursion A recursive function must...

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

View Full Document Right Arrow Icon
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); } }
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/04/2011 for the course CS 2400 taught by Professor Richie during the Spring '11 term at Rensselaer Polytechnic Institute.

Page1 / 9

Lecture-21-Recursion - Recursion A recursive function must...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online