lec12-recursion

lec12-recursion - 1 CSC 1111 Introduction to Computing...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon

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

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

Unformatted text preview: 1 CSC 1111 Introduction to Computing using C++ Recursion 2 Outlines Solving problems recursively How to implement and trace recursive functions Examples 3 Introduction Recursion – a method of defining functions in which the function being defined may be used within its own definition. e.g.: f(N) = N * (N-1) * (N-2) * … * 1 f(N) = N * f(N-1), if N > 1 f(1) = 1 Recursive solution 4 int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } f(4) N = 4 Recursive solution implemented as a C++ function. How should you trace this recursive function? 5 int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } N = 4 N = 3 f(3) The function is not actually "calling itself" but a "clone" of itself. Each "clone" of the function maintains its own set of local variables. 6 int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } N = 4 N = 3 N = 2 f(2) 7 int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1) ; } int f(int N) { if (N == 1) return 1; return N * f(N-1); } f(1) N = 4 N = 3 N = 2 N = 1 8 int f(int N) { if (N == 1) return 1; return N * f(N-1)...
View Full Document

This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

Page1 / 26

lec12-recursion - 1 CSC 1111 Introduction to Computing...

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

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