Previous Lecture Lecture 14 Next Lecture

Lecture 14, Tue 08/21

Recursion

Recursion

Properties of Recursion

Example: Factorial

int factorial (int n) {
	if (n == 1) // base case
		return 1;

	return n * factorial(n – 1);
}
---
int main() {
	cout << factorial(4) << endl; // 24	
}

factorial(4) = 4 * factorial(3)
                   3 * factorial(2)
                       2 * factorial(1)
                           1
                       2 * 1
                   3 * 2
               4 * 6
               24

Example: Fibonacci

int fibonacci(int n) {
	if (n == 1) {
		return 1;
	}
	if (n == 0) {
		return 0;
	}
	retrun fibonacci(n-2) + fibonacci(n-1);
}
-----
int main() {
	cout << fibonacci(4) << endl; 3
}
fib(4)
fib(2)          + fib(3)
fib(0) + fib(1) + fib(3)
0      + 1      + fib(3)
1               + fib(1) + fib(2)
1               + 1      + fib(2)
1               + 1      + fib(0) + fib(1)
1               + 1      + 0      + 1
3

Example: Recursively find the length of a C-string

int recLength(char* s) {
	char temp = *s;

	if (temp != '\0') {
		return 1 + recLength(&s[1]);
	} else {
		return 0;
	}
}
----
char s1[] = {'a', '\0'};
char s2[] = {'\0'};
char s3[] = {'a', 'a', 'a', '\0'};

cout << recLength(s1) << endl;
cout << recLength(s2) << endl;
cout << recLength(s3) << endl;

Example: Recursively search through a Linked List

bool recExists(Node* n, int value) {
	if (n == NULL) {
		return false;
	}

	if (n->data == value) {
		return true;
	}

	return recExists(n->next, value);
}
---
#include "linkedListFuncs.h"

int main() {
	int arr1[3]={73,57,61};
	LinkedList* list1 = arrayToLinkedList(arr1,3);

	cout << recExists(list1->head, 57) << endl; // 1
	cout << recExists(list1->head, 60) << endl; // 0
	cout << recExists(list1->head, 73) << endl; // 1
}

Recursion Performance

Stack Overflow

int factorial (int n) {
/* REMOVE BASE CASE
	if (n == 1) // base case
		return 1;
*/

	cout << n << endl;
	return n * factorial(n – 1);
}