Documente Academic
Documente Profesional
Documente Cultură
cs-Fundamentals.com
Programming Tutorials and Interview Questions
Custom Search
Home
C Programming
Java Programming
Data Structures
Web Development
Tech Interview
point is called base case from where control moves back towards the original problem
by solving sub problems and assembling results in order to get the final result.
/*
File: dec_to_bin.c
Program: decimal to binary conversion
of positive integer (iterative version)
*/
#include <stdio.h>
#include <string.h>
int main ()
{
printf("Binary of 19 is: ");
printBin(19);
printf("\n");
}
void printBin (int n)
{
char binS[256]; //contains binary digits.
int i = 0;
do
{
binS[i++] = n % 2 + '0';
} while (n/=2);
cs-fundamentals.com/c-programming/recursion-in-c.php 2/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
OUTPUT
======
Binary of 19 is: 10011
/*
Demonstration of Recursion in C
File: rec_dec_to_bin.c
Program: decimal to binary conversion
of positive integer (recursive version)
*/
#include <stdio.h>
#include <string.h>
int main ()
{
int n;
printf("Enter an integer: ");
scanf("%d", &n);
printf("Recursively computed binary of %d is: ", n);
recPrintBin(n);
printf("\n");
}
From above pieces of codes, it can be clearly seen that the second piece of code is
more concise and cleaner. However, application of recursion is completely problem
dependent and it may not be suitable for all problem types.
On the contrary, the recursive version does not need any reverse of binary digits
because in recursion, the very last call to function is processed very first, then second
last and so on. This is done with help of a stack of calls, where the last call to function
is placed on top of the stack, therefore processed first. That's how recursion in C is
tackled and processed.
There are some classical examples which can be better implemented using recursion
rather than their iterative counterparts. Towers of Hanoi, recursive listing of
directories or folders and Russian Matryoshka dolls are some of them.
Types of Recursion
A function is recursive if it makes a call to itself directly or indirectly. If a function
f() calls itself within from its own body, it is called recursive. Secondly, if a function
f() calls another function g() that ultimately calls back to f(), then it can also be
cs-fundamentals.com/c-programming/recursion-in-c.php 4/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
Linear Recursion
In linear recursion a function calls exactly once to itself each time the function is
invoked, and grows linearly in proportion to the size of the problem. Finding
maximum among an array of integers could be a good example of linear recursion.
The same is demonstrated below:
Let's assume that we are given an array arr of n decimal integers and we have to
find the maximum element from the given array. We can solve this problem using
linear recursion by observing that the maximum among all integers in arr is arr[0],
if n==1, or the maximum of first n-1 in arr and the last element in arr.
/*
File: rec_max_array.c
Program: Find maximum among array elements
recursively.
*/
#include <stdio.h>
#define SIZE 10
int main ()
{
int arr[SIZE] = {1, 3, 5, 4, 7, 19, 6, 11, 10, 2};
int max = recursiveMax(arr, SIZE);
printf("Maximum element among array items is: %d\n", max);
OUTPUT
======
Maximum element among array items is: 19
cs-fundamentals.com/c-programming/recursion-in-c.php 5/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
Tail Recursion
Tail Recursion is another form of linear recursion, where the function makes a
recursive call as its very last operation. Note that, there is a difference between last
operation and last statement. If you see at recursiveMax (defined above), then you
will find that recursive call to function recursiveMax is last statement but not last
operation, code arr[n-1] yet to be processed to complete the execution of last
statement.
Suppose, we are given an array of decimal integers, and we have to reverse the order
of elements in which they are stored. We can solve this problem by using linear
recursion. Reversal of an array can be achieved by swapping the first and last
elements and then recursively reversing the remaining elements in the array.
/*
File: rec_array_reverse.c
Program: Reverse array elements recursively.
*/
#include <stdio.h>
#define SIZE 10
int main ()
{
int arr[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9 , 10};
int i;
recursiveRev (arr, 0, SIZE-1);
OUTPUT
======
Printing array elements after reversing them...
10
9
8
7
6
5
4
3
2
1
Recursive version of reversing array elements problem can easily be converted into
iterative one as follows:
while (i < j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
But, if you look at the signatures of recursiveRev and iterativeRev you will find a
little difference there, both functions are passed different number of arguments. It is
so, because to facilitate recursion sometimes the problem may need to be redefined.
Binary Recursion
As name suggests, in binary recursion a function makes two recursive calls to itself
when invoked, it uses binary recursion. Fibonacci series is a very nice example to
demonstrate binary recursion. See the example below:
cs-fundamentals.com/c-programming/recursion-in-c.php 7/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each
subsequent number is the sum of the previous two [Definition Source wikipedia].
/*
File: bin_rec_fib.c
Program: Computes n-th fibonacci number using
binary recursion.
*/
#include <stdio.h>
int main ()
{
int n = 6;
printf ("%dth fibonacci number is %d\n", n, recursiveFib(n));
}
OUTPUT
======
6th fibonacci number is 8
Above piece of code exercises binary recursion in order to compute 6th fibonacci
number. In this piece of code recursiveFib returns n in case n is less than or equal
to 1. This is the base condition in recursiveFib from where recursive call returns to
previous call. Following figure shows how recursiveFib is executed.
Multiple Recursion
Multiple recursion can be treated a generalized form of binary recursion. When a
function makes multiple recursive calls possibly more than two, it is called multiple
recursion.
cs-fundamentals.com/c-programming/recursion-in-c.php 8/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
variables. And every call is saved in a stack, where the last most call will be
processed first. Every program maintains a stack (a special area of memory) during
run time to remember where to go back when a function is called.
You can trace a recursive function by pushing every call it makes to a stack and then
come to the previous call when it returns. Look at the following piece of code and try
to trace it; we will do in a moment's time.
#include <stdio.h>
int main()
{
int i = 4, j = 5;
printf("mystery of %d and %d is: %d\n", i, j, mystery (4, 5));
}
OUTPUT
======
mystery of 4 and 5 is: 20
In below figure, I represent each call with a concentric box, where inner boxes will
represent the deeper level of recursion. As you see, in the innermost box recursion
terminates and no further recursive call is made. And, it starts returning to parent
calls ladder by ladder.
cs-fundamentals.com/c-programming/recursion-in-c.php 9/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
There are some data structures you will see which are quite easy to code with help of
recursion. Tree traversals, quick, and merge sort are a few examples.
Despite above benefits, recursion provides no storage saving, nor time. As we have
discussed that every recursive call is saved in a special memory area the program
maintains (i.e., stack). Pushing a call frame to stack and removing it back is time
cs-fundamentals.com/c-programming/recursion-in-c.php 10/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
consuming relative to the record keeping required by iterative solution. There may
be chances your recursive solution results into Stack overflow, in case the number of
recursive calls does not fit into the stack.
Conclusion - Recursion
Hope you have enjoyed reading Recursion in C. Having seen at pros and cons of
recursion, you would have realized that recursion is programmer friendly, not
system because recursive version of a function is shorter to write, cleaner to see, and
easier to maintain. And so, as it is said "anyone can write code that computers can
understand, wise programmers write code that humans can understand." So keep
coding with recursion. And yes, how long do you think the following program will take
to finish its execution?
#include <stdio.h>
int main()
{
printf("num : guessIt(num)\n");
printf("=========================\n");
for (int num = 0; num < 100; num++)
{
printf("\n%3d: %d", num, guessIt(num));
}
}
Last Word
In this tutorial we talked of recursion in C language and how does recursion work?
Then types of recursion (linear, tail, binary, and multiple recursion), tracing
recursive calls, and pros and cons of recursion. Hope you have enjoyed reading this
tutorial. Please do write us if you have any suggestion/comment or come across any
error on this page. Thanks for reading!
References
1. Randal E. Bryant, David R. O'Hallaron, Computer Systems: A Programmer's Perspective
2. Introduction to programming in Java
3. Data Structures and Algorithms in Java (4th edition)
cs-fundamentals.com/c-programming/recursion-in-c.php 11/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
gfi.com
cs-fundamentals.com/c-programming/recursion-in-c.php 12/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
Add a comment...
recursive function fun(n) to print the values 2kn, ...., 22n, 21n, 20n.
cs-fundamentals.com/c-programming/recursion-in-c.php 13/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
0 Comments cs-fundamentals.com
1 Login
ALSO ON CS-FUNDAMENTALS.COM
Why main is public static void in Java Create Custom 404 Error Page in PHP
| Will Java program compile, if main and Apache Using .htaccess
5 comments 3 years ago 2 comments 3 years ago
Has s an Very Good Explanation Manis h thanks. very clear
explanation
Email:
Subscribe
73 1
cs-fundamentals.com/c-programming/recursion-in-c.php 14/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
cs-fundamentals.com/c-programming/recursion-in-c.php 15/16
5/19/17 Types of Recursion in C. Tail Linear Binary Multiple
cs-fundamentals.com/c-programming/recursion-in-c.php 16/16