Recursive void Functions. â» Tracing recursive calls. â» Infinite recursion, overflows. â» Recursive Functions that R
3/24/2013
Structured Programming Using C++ Lecture 6 : Recursive functions
Dr. Amal Khalifa Dr. Safwat Hamad
Lecture Contents:
Recursive void Functions
Recursive Functions that Return a Value
Tracing recursive calls Infinite recursion, overflows Powers function
Thinking Recursively
Recursive design techniques
Dr. Hamad, Dr. Khalifa 13-2
Dr. Amal Khalifa - Spring 2012
1
3/24/2013
Introduction to Recursion
A function that "calls itself"
Said to be recursive In function definition, call to same function
Divide and Conquer
Basic design technique Break large task into subtasks Subtasks could be smaller versions of the original task! Example: Computing global sum of a list
Dr. Hamad, Dr. Khalifa 13-3
Example •Subtask •
Compute sum for 1st half of list
•Subtask •
38
27
43
3
9
82
10
20
1:
2:
Compute sum for 2nd half of list
•Eg:
{38, 27, 43, 3, 9, 82, 10, 20}
13-4
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
2
3/24/2013
Example : Recursive void Function
Write a function that prints a message a specified number of times. Hint: write two versions one iterative and the other recursive.
5
Dr. Hamad, Dr. Khalifa
Recursion—A Closer Look
Computer tracks recursive calls
Stops current function
Must know results of new recursive call before proceeding
Saves all information needed for current call
To be used later
Proceeds with evaluation of new recursive call
When THAT call is complete, returns to "outer" computation
Dr. Hamad, Dr. Khalifa
Dr. Amal Khalifa - Spring 2012
3
3/24/2013
Recursion Big Picture
Outline of successful recursive function:
One or more cases where function accomplishes it’s task by:
Making one or more recursive calls to solve smaller versions of original task
Called "recursive case(s)"
One or more cases where function accomplishes it’s task without recursive calls
Called "base case(s)" or stopping case(s) Base case MUST eventually be entered If it doesn’t Recursive calls never end! infinite recursion Dr. Hamad, Dr. Khalifa 13-7
Example : Vertical Numbers Write a function writeVertical(num) that displays the digits of given number vertically, one per line. Example : >>1234 1 2 3 4 8
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
4
3/24/2013
Recursive Definition
Break problem into two cases
Simple/base case:
Recursive case:
if n=10 two subtasks:
1- Output all digits except last digit 2- Output last digit
Example: argument 1234:
1st subtask displays 1, 2, 3 vertically 2nd subtask displays 4
13-9
Dr. Hamad, Dr. Khalifa
Function Tracing !! void writeVertical(int n) { if (n < 10) //Base case cout