In this article recursion in c we give the information about In C language, Recursion is a process in which a function calls itself repeatedly. This function is called recursive function.

Recursion in C:

In C language, Recursion is a process in which a function calls itself repeatedly. This function is called recursive function.

This type of function call is called recursive calls. There are many recursive calls in recursion, hence to terminate it it is necessary to use terminate condition.

We cannot apply recursion to all problems but by using it we can solve some problems easily. For example – we can use it to solve problems like sorting, searching, traversal etc.

C programming language supports recursion. But while using it, it is necessary for the programmer to define the exit condition in the function, otherwise it will continue in infinite loop.

Recursive functions are very useful in solving many mathematical problems such as calculating the factorial of a number, generating Fibonacci series etc.

Recursion function Syntax –

void recurse()

{

    … .. …

    recurse();

    … .. …

}

int main()

{

    … .. …

    recurse();

    … .. …

}

Program – finding the factorial of a number using recursion

#include<stdio.h>

long factorial(int n)

{

  if (n = = 0)

    return 1;

  else

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

}

void main()

{

  int number;

  long fact;

  printf(“Enter a number: “);

  scanf(“%d”, &number);

 fact = factorial(number);

 printf(“Factorial of %d is %ld\n”, number, fact);

 return 0;

}

O/P –

Enter a number: 5
Factorial of 5 is 120

Advantage of Recursion:

  1. It reduces unnecessary function calls.
  2. Through this we can solve problems easily because iterative solution is very big and complex.
  3. It makes our code elegant.

Disadvantages of Recursion:

  1. It is difficult to understand and debug a program created using recursion.
  2. For this we need more memory space.
  3. It takes more time to execute the program.

Recursion program

#include <stdio.h>

int sum(int n);

void main()

 {

    int number, result;

    printf(“Enter a positive integer: “);

    scanf(“%d”, &number);

    result = sum(number);

    printf(“sum = %d”, result);

}

int sum(int n)

{

    if (n != 0)

        // sum() function calls itself

        return n + sum(n-1);

    else

        return n;

}

Output -:

Enter a positive integer:5

sum = 15

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Join Now: Data Warehousing and Data Mining 

Leave a Reply

Your email address will not be published. Required fields are marked *