CP1_12_Recursion_1112

# CP1_12_Recursion_1112 - Recursion Recursion Recursion...

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

Recursion

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

View Full Document
Recursion – what is it? With functions we saw that a basic approach to problem solving is to “divide and conquer” : break the problem into sub-problems, solve the sub-problems and then combine those solutions to create a solution to the original problem. Sometimes, we find that one or more of the sub- roblems is a smaller example of the original problem problems is a smaller example of the original problem. In such cases we can apply the powerful problem solving pp y p p g technique of recursion to complete the task using recursive functions. A recursive function is a function defined in terms of itself. So, the function definition contains a call to itself. 2 CSIS1117B Computer Programming 1 2011-2012
Example To apply the technique: first identify the recursive structure of the problem. Once the recursive structure is known, the resulting program is usually very simple. or example suppose we want to compute the ositive For example, suppose we want to compute the positive exponentiation of a number y: y n = y y y , where n >= 0 . If n equals 0 , y 0 = 1 f quals y If n equals 1 , y 1 = y y 0 If n equals 2 , y 2 = y y 1 If n equals k , y k = y y k-1 We can express y k in terms of an expression involving y k-1 . hus by solving the sub roblem we also solve the Thus by solving the sub-problem, we also solve the original problem. 3 CSIS1117B Computer Programming 1 2011-2012

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

View Full Document
Defining a recursive function General approach for defining a function recursively: 1. Identify the Base Case : Find the simplest case(s) of the problem E.g If n equals 0 , y 0 = 1 2. Identify the Recursive Case : Find the rule for solving the problem if the sub- problem(s) is solved E.g. Express y k in terms of y k-1 4 CSIS1117B Computer Programming 1 2011-2012
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 16

CP1_12_Recursion_1112 - Recursion Recursion Recursion...

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

View Full Document
Ask a homework question - tutors are online