You are on page 1of 13

Recursion in C

Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem. Any function which calls itself is called recursive
function, and such function calls are called recursive calls. Recursion involves several
numbers of recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is
difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks
that can be defined in terms of similar subtasks. For Example, recursion may be
applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is
always overhead. Any problem that can be solved recursively, can also be solved
iteratively. However, some problems are best suited to be solved by the recursion,
for example, tower of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

1. #include <stdio.h>  
2. int fact (int);  
3. int main()  
4. {  
5.     int a,f;  
6.     printf("Enter the number whose factorial you want to calculate?");  
7.     scanf("%d",&a);  5
8.     f = fact(a);  
9.     printf("factorial = %d",f);  
10. }  
11. int fact(int n)  
12. {  
13.     if (n==0)  
14.     {  
15.         return 1;  
16.     }  
17.     
18.     
19.     else   
20.     {  
21.         return (n*fact(n-1)); 
22.     }  
23. }  
We can understand the above program of the recursive method call by the figure given
below:
Let's see an example to find the nth term of the Fibonacci series.

1. #include<stdio.h>  
2. int fibonacci(int);  
3. void main ()  
4. {  
5.     int n,f,i;  
6.     printf("Enter the value of n?");  
7.     scanf("%d",&n);  
8. For(i=0;i<n;i++)
9. {
10.  f = fibonacci(i);  
11.     printf("Fibonacci(%d)=%d",i,f);  
12. }  
13. }
14. int fibonacci (int n)  
15. {  
16.     if (n==0)  
17.     {  
18.     return 0;  
19.     }  
20.     else if (n == 1)  
21.     {  
22.         return 1;   
23.     }  
24.     else  
25.     {  
26.         return fibonacci(n-1)+fibonacci(n-2);  
27.     }  
28. }  

Output
Ackermann Function
In computability theory, the Ackermann function, named after Wilhelm
Ackermann, is one of the simplest and earliest-discovered examples of a
total computable function that is not primitive recursive. All primitive recursive
functions are total and computable, but the Ackermann function illustrates
that not all total computable functions are primitive recursive. Refer this for
more.
It’s a function with two arguments each of which can be assigned any non-
negative integer.

The intuitive reason for why it is not primitive recursive is that it is recursing on more than
one parameters, the primitive recursive functions are defined by functions recursing on
only one parameter.

Solve A(1, 2)?


Answer:
Given problem is A(1, 2)
Here m = 1, n = 2 e.g m > 0 and n > 0
Hence applying third condition of Ackermann function
A(1, 2) = A(0, A(1, 1)) ———- (1)
Now, Let’s find A(1, 1) by applying third condition of Ackermann function
A(1, 1) = A(0, A(1, 0)) ———- (2)
Now, Let’s find A(1, 0) by applying second condition of Ackermann function
A(1, 0) = A(0, 1) ———- (3)
Now, Let’s find A(0, 1) by applying first condition of Ackermann function
A(0, 1) = 1 + 1 = 2
Now put this value in equation 3
Hence A(1, 0) = 2
Now put this value in equation 2
A(1, 1) = A(0, 2) ———- (4)
Now, Let’s find A(0, 2) by applying first condition of Ackermann function
A(0, 2) = 2 + 1 = 3
Now put this value in equation 4
Hence A(1, 1) = 3
Now put this value in equation 1
A(1, 2) = A(0, 3) ———- (5)
Now, Let’s find A(0, 3) by applying first condition of Ackermann function
A(0, 3) = 3 + 1 = 4
Now put this value in equation 5
Hence A(1, 2) = 4
So, A (1, 2) = 4

Question: Solve A(2, 1)?


Answer: 5
Question: Solve A(2, 2)?
Answer: 7

C program to illustrate Ackermann function


  
#include <stdio.h>
int ack(int m, int n)
{
    if (m == 0){
        return n+1;
    }
    else if((m > 0) && (n == 0)){
        return ack(m-1, 1);
    }
    else if((m > 0) && (n > 0)){
        return ack(m-1, ack(m, n-1));
    }
}
  
int main(){
    int A;
    A = ack(1, 2);
    printf("%d", A);
    return 0;
}
Quicksort algorithm is based on the divide and conquer approach where
1. An array is divided into subarrays by selecting a pivot element (element
selected from the array).
While dividing the array, the pivot element should be positioned in such a
way that elements less than pivot are kept on the left side and elements
greater than pivot are on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This
process continues until each subarray contains a single element.

3. At this point, elements are already sorted. Finally, elements are combined
to form a sorted array.

Working: Quicksort Algorithm

1. Select the Pivot Element


There are different variations of quicksort where the pivot element is
selected from different positions. Here, we will be selecting the rightmost
element of the array as the pivot element.

Select a pivot element

2. Rearrange the Array


Now the elements of the array are rearranged so that elements that are
smaller than the pivot are put on the left and the elements greater than the
pivot are put on the right.
Put all the smaller
elements on the left and greater on the right of pivot element

Here's how we rearrange the array:

1. A pointer is fixed at the pivot element. The pivot element is compared with
the elements beginning from the first index.

Comparison of
pivot element with element beginning from the first index

2. If the element is greater than the pivot element, a second pointer is set for

that element. If
the element is greater than the pivot element, a second pointer is set for
that element.

3. Now, pivot is compared with other elements. If an element smaller than the
pivot element is reached, the smaller element is swapped with the greater
element found earlier.
Pivot is compared
with other elements.

4. Again, the process is repeated to set the next greater element as the
second pointer. And, swap it with another smaller element.

The process is
repeated to set the next greater element as the second pointer.

5. The process goes on until the second last element is reached.

The process goes


on until the second last element is reached.
6. Finally, the pivot element is swapped with the second pointer.

Finally, the pivot


element is swapped with the second pointer.

3. Divide Subarrays
Pivot elements are again chosen for the left and the right sub-parts
separately. And, step 2 is repeated.

Select pivot element of


in each half and put at correct place using recursion

The subarrays are divided until each subarray is formed of a single


element. At this point, the array is already sorted.

Quick Sort Algorithm

quickSort(array, leftmostIndex, rightmostIndex)


if (leftmostIndex < rightmostIndex)

pivotIndex <- partition(array,leftmostIndex, rightmostIndex)

quickSort(array, leftmostIndex, pivotIndex - 1)

quickSort(array, pivotIndex, rightmostIndex)

partition(array, leftmostIndex, rightmostIndex)

set rightmostIndex as pivotIndex

storeIndex <- leftmostIndex - 1

for i <- leftmostIndex + 1 to rightmostIndex

if element[i] < pivotElement

swap element[i] and element[storeIndex]

storeIndex++

swap pivotElement and element[storeIndex+1]

return storeIndex + 1

Visual Illustration of Quicksort Algorithm

You can understand the working of quicksort algorithm with the help of the
illustrations below.
Sorting the elements on the left of pivot using recursionSorting the elements on the right of pivot
using recursion

// Quick sort in C

#include <stdio.h>

// function to swap elements


void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to find the partition position


int partition(int array[], int low, int high) {

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

You might also like