codescracker


c

C Recursion



« Previous Tutorial Next Tutorial »


Recursion is the process in which function calls itself again and again until the condition becomes false. In other words, if a program allows you to call a function inside the same function that is called recursive call of the function shown as follows.

void recursion()
{
   recursion();   // function calls itself
}

int main()
{
   recursion();
}

Java Recursion Example

Here is an example program, helps you in understanding the concept of recursion in C. This C program find factorial of a number using recursion:

/* C Recursion - This program is to
 * calculate factorial of a Number
 * using recursive function
 */

#include<stdio.h>
#include<conio.h>

int fact(unsigned int i)
{
	if(i <= 1)
	{
		return 1;
	}
	return i*fact(i-1);
}
void main()
{
	int num;
	clrscr();

	printf("Enter a Number : ");
	scanf("%d", &num);
	printf("Factorial of %d is %d\n", num, fact(num));

	getch();
}

Here is the sample run of the above C program:

c recursion

Now, here is another program, prints Fibonacci series using recursion in C:

/* C Recursion - This program find
 * the Fibonacci series upto the
 * given term using recursion
 */

#include<stdio.h>
#include<conio.h>

int fib(int i)
{
	if(i==0)
	{
		return 0;
	}
	if(i==1)
	{
		return 1;
	}
	return fib(i-1)+fib(i-2);
}

void main()
{
	int i, limit;
	clrscr();

	printf("Upto how many term ? ");
	scanf("%d", &limit);

	for(i=0; i<limit; i++)
	{
		printf("%d  ", fib(i));
	}

	getch();
}

Here is the sample run of the above C program:

c recursive function

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test