Recursion Fall 2008

Post on 05-Jan-2016

33 views 0 download

Tags:

description

Recursion Fall 2008. Dr. David A. Gaitros dgaitros@admin.fsu.edu. Recursion. “ This is the song that never ends, Yes it goes on and on my friend. Some people started singing it, not knowing what it was, And they'll continue singing it forever just because -> ” - PowerPoint PPT Presentation

Transcript of Recursion Fall 2008

RecursionFall 2008

Dr. David A. Gaitrosdgaitros@admin.fsu.edu

Recursion

“This is the song that never ends, Yes it goes on and on my friend. Some people started singing it, not knowing what it was, And they'll continue singing it forever just because -> ”

Written and composed by Norman Martin

Recursion

• A program or function that has the ability to call itself is said to be recursive.

• Mathematically, recursion is very interesting and has been around for quite some time. – Take the Fibonacci numbers. A

Fibonacci number is the sum of the two previous numbers

fn = fn-1 + fn-2

• Recursion is very useful in traversing tree structures

Simple Example

#include <iostream>

using namespace std;

int SubtractOnetoZero

int main(void)

{

int x=10;

cout << “final number is “ <<

<< SubtractOnetoZero(x)

<< endl;

return 0;

}

int SubtractOnetoZero(int x)

{

if(x==1) return 0;

else return SubtractOnetoZero(x-1);

}

Recursive Routine

• A recursive routine will be one that has at least one function call in it to itself.

• To behave properly, the routine must have some method to stop the recursion.

• There is almost always some type of parameter passed.

• Recursive routines almost always return some type other than void.

Recursive Routines(some facts)

• Not used often except in data structure tree traversal.

• any problem that can be coded with a recursive routine can be done interatively with a loop

• Recursive functions are easier to write• Recursive functions are usually smaller• Recursive functions have much more

overhead because of function calls. • Iterative routines are usually more efficient

in the amount of memory used. • Iterative routines usually run more efficiently

Examples

// Recursive Fibonnaci function

int Fiv (int n)

{

if (n<= 0) return 0;

else if (n==1) return 1;

else return Fib (n-1) + Fib (n-2);

}

Examples

// Iterative Fibonnaci function

int Fib(int n)

{

int n1=1, n2=2, n3;

int i=2;

while (I < n);

{

n3=n1+n2;

n1=n2;

n2=n3;

i++;

}

return n2;

}