{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture-21-Recursion

# Lecture-21-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

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.

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online