You are on page 1of 8

Recursion

1 CUIT114/111 SEST, CUT 3/1/2017


Outline
 Recursion
 Recursive definitions
 Example: Factorial function
 Common uses for recursion

2 CUIT114/111 SEST, CUT 3/1/2017


Recursion
 When you define something in terms of sub-versions of itself
 Example 1:
 Great Grandmother = parent to grandma Sophie
 Grandma Sophie = parent to mom Sipho
 Mom Sipho = parent to Me
 Me = parent to Tinashe
 Tinashe = parent to ...
 The next generation will defined in term of Parent to definition
 Example 2
 You are royal if your parents are royal
 Your parents are royal if their parents are royal
 Your grandparents are royal if ... and so on.
 Must stop at some point
 So that the final fact is established
 Example 2: terminates when without a doubt one of the ancestors is records as King so-
and-so or something like that.

3 CUIT114/111 SEST, CUT 3/1/2017


Recursive definitions
 Two parts
 Definition of repeating state
 Often expressed in smaller or sub-versions of itself
 Definition of terminating condition
 Often expressed as a fixed value

4 CUIT114/111 SEST, CUT 3/1/2017


Fibonacci numbers
 A fibonacci number is a positive number that is the sum of its two previous numbers
 The first two numbers in fibonacci are 0 (0th term) and 1(1st term)
 Hence the 3rd fibonacci number is 0+1 = 1
 The repeating formula is
 The nth number = the sum of the (n-1)th number and the (n-2)th number
 The calculation of the 4th number is
 0 1 (n-2)th (n-1)th (4th)
 = (n-1)th + (n-2)th
 = (n-2)th + 1 + (0 + 1)
 = (0 + 1) + 1 + (1)
 = 2 + (1)
 =3
 So what does it look like mathematically?
 f(n) = f(n-1) + f(n-2) where f(x) means xth term
 f(0) = 0, f(1) = 1

5 CUIT114/111 SEST, CUT 3/1/2017


Fibonacci code (1)
 Given  We can now write
 f(x) = f(x-1) + f(x-2) where
f(x) means xth term
 f(0) = 0, f(1) = 1
 f(x) gives an integer result
for the xth term

6 CUIT114/111 SEST, CUT 3/1/2017


Fibonacci code (2)
1. #include <stdio.h>
2. int fib; //result of f(x)

3. int f(int n) //f(n)


4. { if (n == 0) return 0; //f(0) =0
5. else if (n==1) return 1; //f(1)=1
6. else return (f(n-1)+f(n-2)); //f(n) = f(n-1) + f(n-2) for any other
7. }
8. int main()
9. { int term = -1;
10. while (term < 0)
11. { printf("Enter position of fibonacci term (0 means position 0): ");
12. scanf("%d",&term);
13. }
14. if (term > -1) printf("Fibonacci(%d) = %d",term, f(term));
15. return 0;
16. }

7 CUIT114/111 SEST, CUT 3/1/2017


Common uses for recursion
 String manipulation
 E.g. Displaying string in reverse
 E.g. Finding depth at which spaces are encountered within a
string
 Searching
 Sorting
 File processing
 Data structures (trees, heaps, etc.)
 Complex problems (divide and conquer)

8 CUIT114/111 SEST, CUT 3/1/2017

You might also like