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  write number n to screen 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 << n << endl; else { //Recursive step writeVertical(n/10); cout <<(n%10)<
13-10

Dr. Amal Khalifa - Spring 2012

writeVertical(123)

writeVertical(12)





writeVertical(1)



cout << 1 << endl;

cout << 2 << endl;

cout

<< 3 << endl;

•What

happens if base case omitted??

Dr. Hamad, Dr. Khalifa

5

3/24/2013

Stacks for Recursion 

A stack  

Specialized memory structure Like stack of paper  





Place new on top Remove when needed from top

Called "last-in/first-out" memory structure

Recursion uses stacks  

Each recursive call placed on stack When one completes, last call is removed from stack

Dr. Hamad, Dr. Khalifa 13-11

Stack Overflow 

Size of stack limited 



Long chain of recursive calls continually adds to stack 



All are added before base case causes removals

If stack attempts to grow beyond limit: 



Memory is finite

Stack overflow error

Infinite recursion always causes this

Dr. Hamad, Dr. Khalifa 13-12

Dr. Amal Khalifa - Spring 2012

6

3/24/2013

Recursion Versus Iteration   

Recursion not always "necessary" Not even allowed in some languages Any task accomplished with recursion can also be done without it 



Nonrecursive: called iterative, using loops

Recursive:  

Runs slower, uses more storage Elegant solution; less coding

Dr. Hamad, Dr. Khalifa 13-13

It’s break time!! See you…..

14

Dr. Amal Khalifa - Spring 2012

Dr. Hamad, Dr. Khalifa

7

3/24/2013

Recursive Functions with return Recursion not limited to void functions Can return value of any type Same technique, outline:

  

1.

One+ cases where value returned is computed by recursive calls 

2.

Should be "smaller" sub-problems

One+ cases where value returned computed without recursive calls 

Base case

Dr. Hamad, Dr. Khalifa 13-15

base exp = base * base exp-1

Recursive power()

int power (int x, int n)

function power(base, p):

{





if (n<0) { cout << "Illegal argument"; exit(1); } if (n>0) return (power(x, n-1)*x); else return (1); }

13-16

Dr. Amal Khalifa - Spring 2012

  

Returns base raised to p Returns double value power(x, n – 1) * x power(2,3);  power(2,2)*2  power(2,1)*2 power(2,0)*2 1

Dr. Hamad, Dr. Khalifa

8

3/24/2013

Tracing Function power(2,3)

13-17

Dr. Hamad, Dr. Khalifa

Thinking Recursively 

Ignore details    



Forget how stack works Forget the suspended computations Yes, this is an "abstraction" principle! And encapsulation principle!

Let computer do "bookkeeping" 

Programmer just think "big picture"

Dr. Hamad, Dr. Khalifa 13-18

Dr. Amal Khalifa - Spring 2012

9

3/24/2013

Recursive Design Techniques  

Don’t trace entire recursive sequence! Just check 3 properties: 1. 2. 3.

No infinite recursion Stopping cases return correct values Recursive cases return correct values

Dr. Hamad, Dr. Khalifa 13-19

Recursive Design Check: power() 

Check power() against 3 properties: 1.

No infinite recursion:  

2.

3.

2nd argument decreases by 1 each call Eventually must get to base case of 1

Stopping case returns correct value: 

power(x,0) is base case



Returns 1, which is correct for x0

Recursive calls correct: 

For n>1, power(x,n) returns power(x,n-1)*x



Plug in values  correct

Dr. Hamad, Dr. Khalifa 13-20

Dr. Amal Khalifa - Spring 2012

10

3/24/2013

Example: factorials Write a function factorial(num) that recursively computes the factorial of an integer. Hint : N! = 1 x 2 x 3 x 4 ……(N-1) x N

21

Dr. Hamad, Dr. Khalifa

That’s all for today !! Thanks…..

22

Dr. Amal Khalifa - Spring 2012

Dr. Hamad, Dr. Khalifa

11

Structured Programming Using C++ Lecture Contents

Recursive void Functions. ▻ Tracing recursive calls. ▻ Infinite recursion, overflows. ▻ Recursive Functions that Return a Value. ▻ Powers function. ▻ Thinking ...

516KB Sizes 1 Downloads 101 Views

Recommend Documents

A Structured Programming Approach Using C ...
Book synopsis. The third edition of Computer Science: A Structured Programming Approach Using C continues to present both computer science theory and ...

Lecture Contents
May 12, 2012 - 3. Structure data type. Dr. Amal Khalifa, 2012. 5. Structure data Types. Dr. Amal Khalifa, 2012. 6. Type definition. Variable declaration. Member access ... 7 struct CDAccountV1 ←Name of new "type". { double balance;. ← member name

Abstract Contents Genetic Programming - Cartesian Genetic ...
Jul 7, 2010 - Dept of Computer Science. Memorial ... ❖The automatic evolution of computer programs .... P ro ba bilit y o f S uc c e s s f o r 10 0 R uns. 0.2. 0.4.

Abstract Contents Genetic Programming
Jul 7, 2010 - algorithm, Genetic Programming and Evolvable Machines (2009) Vol. 10. For further info see: http://dipaola.org/evolve/. 4. DiPaolo S. Evolving Creative Portrait Painter Programs using Darwinian Techniques with an. Automatic Fitness Func

PDF Programming: Principles and Practice Using C++ ...
C++ (C++11 and C++14) The book is an introduction to programming in general, ... For Beginners-And Anyone Who Wants to Learn Something New The book is ...

PdF Programming: Principles and Practice Using C++
for work in software development or in some other technical field. Focus on. Fundamental Concepts and. Techniques The book explains fundamental concepts ...

Abstract Contents Genetic Programming - Cartesian Genetic ...
Jul 7, 2010 - Abstract. Cartesian Genetic Programming is a form of genetic ... 3. / Divide data presented to inputs (protected) ..... The To Do list isn't too big.