In this lecture, we introduce recursion, and we discuss how to think recursively.
Last lecture
Midterm revision.
Today
Recursion.
Recursion
Recursion is a programming technique that involves solving a problem by breaking it into a smaller problem repeatedly until it is small enough to be solved easily. Solutions of smaller problems can then be combined to form the solution of the original bigger problem.
Example
Write a function that gets the factorial of n recursively.
Recursively get the factorial of a smaller number.
Repeat until we reach the terminating case.
Combine the solutions to get the bigger problem’s solutions.
int factorial(int n){if(n ==1|| n ==0){return1;// base case}else{return n * factorial(n -1);// recursive case}}int main(){int f = factorial(3);// f = 6return0;}
The call to factorial(3) would create recursive function calls.
int factorial(int3){if(3==1||3==0){return1;// base case}else{return3* factorial(3-1);// recursive case}}int factorial(int2){if(2==1||2==0){return1;// base case}else{return2* factorial(2-1);// recursive case}}int factorial(int1){if(1==1||1==0){return1;// base case}else{return1* factorial(1-1);// recursive case}}
Example
Given an array of n integers, sum the elements of the array.
int sumOfArray(int a[],int left,int right){if(left == right){return a[left];}else{return a[left]+ sumOfArray(a, left +1, right);}}We need to communicate to the next recursive function call from where should westart adding and until where (e.g.`left`and`right`).::::::{.callout-note icon=false}## ExamplePrint nodes in a linked list recursively.<img src="diagrams/lecture18-diagram1.svg" alt="diagrams/lecture18-diagram1.svg">```cppclass Node {public:int data; Node* head;};void rprint(Node* p){if(p == NULL){return;// base case}else{ cout << p->data; rprint(p->next);// recursive case}}int main(){ List L;... rprint(L->getHead());// L->getHead() = Node*...}