What is recursive function in C - Definition, Explanation and Examples

What is recursive function in C - Definition, Explanation and Examples

 What is the Recursive function in C

The recursive function in C is that function which calls itself directly or indirectly to solve a smaller version of its task. Recursion can be regarded as the ability of function defining an object in terms of a simpler case of itself. A function calls itself repeatedly until some specified condition has been satisfied. For the problem to solve recursively two condition must be satisfied.

·        The function should have a stopping condition.

·        The program must be written in previous result.

Working mechanism of recursive function



The recursion is repeated until given condition meet.

It has use if else statement or similar approach is use to define certain condition.


Example

Write a C program to find factorial of a number given by the user using recursive function

#include<stdio.h>

#include<conio.h>

int fac(int);

void main()

{

          int n, f;

          printf("\n Enter a number");

          scanf("%d",&n);

          f=fac(n);

          printf("\n Factorial of a number=%d",f);

          getch();

}

int fac(int n)

{

          if(n<=1)

          {

                   return(1);

          }

          else

          {

                   return(n*fac(n-1));

          }

}


Output

 


From the above program of factorial, the factorial of a number n expressed as a series of repetitive multiplication as

Factorial of n = n*(n-1)*(n-2)*(n-3)……………………………….1

Example

Factorial of 3= 3*2*1=6

Let We see how the recursion works. Assume n=3since the value of n is not less than 1, the statement

fac=n*fac(n-1);

Will be executed with n=3. That is,

fac=3*fac(2);

Will be evaluated. The expression on the right-hand side includes a call to facwith n=2 This will return the following value:

2*fac(1);

Once again, fac is called with n = 1. This time the function returns 1. The sequence of operation can be summarized as follows:

fac = 3*fac(2)

      = 3*2*fac(1)

      = 3*2*1;

      =6


Let us see another example

Write a C program to calculate sum of n natural numbers using recursive function

#include<stdio.h>

#include<conio.h>

int sum(int);

void main()

{

          int n, s;

          printf("\n Enter a number");

          scanf("%d",&n);

          s=sum(n);

          printf("\n sum of %d numbers=%d",n,s);

          getch();

}

int sum(int n)

{

          if(n<=0)

          {

                   return(0);

          }

          else

          {

                   return(n+sum(n-1));

          }

}

 Output

Write a C program to calculate sum of n natural numbers using recursive function



Also, check 

function in C 

Click here


 

 

 

 

Post a Comment

0 Comments