recursion in c

Recursion in c a function is called ‘recursive’ if a statement within the body of a function calls the same function

Recursion in c example using factorial programme

factorial of a number is the product of all the integers between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for factorial. Thus factorial of a number can be expressed in the form of itself. Hence this can be programmed using recursion. However, before we try to write a recursive function for calculating factorial let us take a look at the non-recursive function for calculating the factorial value of an integer.

main( ) 
{ 
 int a, fact ; 
 printf ( "\nEnter any number " ) ; 
 scanf ( "%d", &a ) ; 
 fact = factorial ( a ) ; 
 printf ( "Factorial value = %d", fact ) ; 
} 
factorial ( int x ) 
{ 
 int f = 1, i ; 
 for ( i = x ; i >= 1 ; i-- ) 
 f = f * i ; 
 return ( f ) ; 
} 

And here is the output…

Enter any number 3
Factorial value = 6

more example of recursion in c

#include <stdio.h>
 /* printd: print n in decimal */
 void printd(int n)
 {
 if (n < 0) {
 putchar('-');
 n = -n;
 }
 if (n / 10)
 printd(n / 10);
 putchar(n % 10 + '0');
 }

quicksort example using recursion in c

void qsort(int v[], int left, int right)
 {
 int i, last;
 void swap(int v[], int i, int j);
 if (left >= right) /* do nothing if array contains */
 return; /* fewer than two elements */
 swap(v, left, (left + right)/2); /* move partition elem */
 last = left; /* to v[0] */
 for (i = left + 1; i <= right; i++) /* partition */
 if (v[i] < v[left])
 swap(v, ++last, i);
 swap(v, left, last); /* restore partition elem */
 qsort(v, left, last-1);
 qsort(v, last+1, right);
 }

Leave a Comment