Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Tuesday, 14 November 2017

What is Recursion in C Language with Example


Recursion in C

Recursion in  C Language

When function calling itself is called recursion in c programming language. In other words, When function is call in the same function is known as recursion in c language.

The function which calls the same function is called recursive function in C.

Recursive functions is quite useful in any mathematical calculation for solving a problem e.g useful in calculate factorial of any number, perform fibonacci series, etc.

After explaining recursion in c, Let's see the syntax of recursion in c.

Syntax:

function()
{
function();//calling itself, known as recursion or recursive function
}

Let's talk about some advantages and disadvantages of recursion in c language.


Advantages of Recursion in C

There are some advantages of using recursion in c language.
  • Recursion will be useful when same kind of work has to be continued for a finite no input or time.
  • We can reduce the length of the code by using recursion in c.
  • Recursion is very useful for solving data structure problems.

Disadvantages of Recursion in C

There are some disadvantages of recursion in c language.
  • It requires more memory because recursive calls along with automatic variables are stored on the stack.
  • Recursive solution is always logical and it is very difficult to trace i.e debug and analyse.

Now let's explain recursion in c with examples.

Factorial using recursion in c

This is the simple factorial program with recursion in c language.

#include<stdio.h>
#include<conio.h>
int fact(int);

void main()
{
int number, a;
clrscr();
printf("Enter number");
scanf("%d", &number);

a = fact(number);
printf("Factorial is %d\n", a);
getch();
}

int fact(int x)
{
int f;
if(x ==1)
return 1;
else
f = x*fact(x - 1);//recursion performed
return f;
}
}

Output: Enter number 5
             Factorial is 120


Fibonacci Series Program in C with Recursion

This is simple fibonacci series program in c by using recursion function.

#include<stdio.h>
int fibonacci(int);

main()
{
int n, c, i = 0;
scanf("%d", &n);
printf("febonacci series \n");

for(c = 1; c <= n; c++)
{
printf("%d\n", febonacci(i));
i++;
}

return 0;
}

int febonacci(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
else 
return (febonacci(n-1) + febonacci(n-2));
}

Here we discussed what is recursion in c language with examples and their advantages and disadvantages.

Check other C tutorial articles e.g data types in c language and printf() and scanf() function in c.





Share:

0 comments:

Post a Comment

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate