×

Recursion in C

Recursion in C: In the C programming language, the concept known as recursion exists that is a technique in which a function calls itself either directly or indirectly. It allows the developer to express the operations within the terms of themselves. The concept of recursion is a process that comes into the picture when any of the underlying functions call a copy of itself in order to work on a similar type of query.

Any function in a program that calls itself is termed a recursive function, and the function calls are referred to as recursive calls. The recursion indulges numerous recursive calls in its lifetime. However, it is tedious to terminate such recursion conditions.

Recursive codes are shorter when compared with iterative code, but it isn't easy to understand in general.Recursion is a type of algorithm that cannot be applied to every problem.

Although it is more beneficial for problems defined in terms of subproblems such as, it can be applied to many problems that include traversal, sorting techniques, searching, etc. It can be concluded that iterative solutions are more efficient than recursion as the function call is always overhead.

A simple way of learning recursion is to imagine them being in a process where one of the instructions is set to repeat themselves. This concept sounds very much similar to looping as it repeats the same code.

On the contrary, a recursion makes it easier to express the ideas in which the result of the recursive call is necessary to complete a particular work. However, the program or the process can complete without the intervention of a recursive call.

Usage of a recursive algorithm to solve the problem is relatively easy. All the problems which can be solved recursively can be solved iteratively, but all the problems solved iteratively cannot be solved recursively.

Recursion is best acquainted for solutions, problem statements that include the tower of Hanoi, Fibonacci series, factorial, inorder or postorder or preorder tree traversals, graphs, and so on.

Syntax

 void recursion(void)
 {
 recursion(); /* function calls itself */
 }
 int main(void)
 {
 recursion();
 return 0;
 } 

When recursion is being implemented, one must be careful in deliberating an exit condition, or a terminating condition form the recursive function; else, it will continue as an infinite loop.

Recursive Function

Recursive functions perform tasks by dividing them into subtasks. There will be termination conditions defined in the function, which will be satisfied by some of the subtasks. In some cases, the function may not recur referred to as a base class, while some cases where the function keeps calling the same function to perform a sub task is referred to as a recursive case.

 if (base1 test)
 {
 return first_value;
 }
 else if (base2 test)
 {
 return second_value;
 }
 else
 {
 /* solution for problem statement */
 recursive calls;
 } 

Recursion keeps on running until an exit condition is met. In order to prevent the infinite recursion, the “if..else” statement is used where one uses a recursive call while the other does not.

Example of a recursive function for getting sum of numbers

 #include <stdio.h>
 #inlcude<conio.h>
 int sum(int n);
 int main()
 {
 int number, result;
 printf("Enter a positive integer: ");
 scanf("%d", &number);
 result = sum(number);
 printf("sum = %d", result);
 return 0;
 }
 int sum(int n) {
 if (n != 0)
 /* sum() function calls itself */
 return n + sum(n-1);
 else
 return n;
 } 

Output

Recursion in C

In the above given instance, the function ‘sum()’ is being called from the main() function along with the ‘number’ passed as an argument. If the value of the variable ‘n’ within the function ‘sum()’ is 3 in the beginning, in the next call, 2 will be passed to the ‘sum()’ function.

This will continue until the variable ‘n’ becomes 0. Once the value of the variable ‘n’ is equal to 0, then the ‘if’ loop fails, and then the ‘else’ loop will be executed by terminating the program and returning the sum of the integers to the ‘main()’ function.

Factorial of a number

 #include <stdio.h>
 #inlcude<conio.h>
 int f(int n)
 {
             if (n == 0 || n == 1) /*terminating or exit condition
                         return 1;
             else
                         return n * f(n - 1); /* Recursive condition */
 }
 int main()
 {
             int n = 5;
             printf("The factorial of the number %d is: %d", n, f(n));
             return 0;
 } 

Output

Recursion in C

A Fibonacci sum of a series

 #include<stdio.h>
 #include<conio.h>
 int fibonacci(int); 
 void main () 
 { 
 int n,f; 
 printf("Enter the value of the number 'n': "); 
 scanf("%d",&n); 
 f = fibonacci(n); 
 printf("%d",f); 
 } 
 int fibonacci (int n) 
 { 
 if (n==0) 
 { 
 return 0; 
 } 
 else if (n == 1) 
 { 
 return 1;  
 } 
 else 
 { 
 return fibonacci(n-1)+fibonacci(n-2); 
 } 
 }  

Output

Recursion in C

Advantages of using recursion

  • Recursion makes the program look more elegant.
  • The performance of the recursion is vital as it uses loops.
  • It reduces the time complexity.
  • It is the best concept to use in the tree traversal.
  • It gives clarity and reduces the debugging time.

Disadvantages of using recursion

  • It uses more memory than required.
  • It keeps on looping until the termination condition is met.

Related Topics

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime. Dynamic memory allocation helps us to...

4 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

C Pointers

Pointers in C A pointer is a variable, which contains the address of another variable, i.e., it’s a variable which has the address of another variable as its value. The utilization...

4 minutes read.

strtok() and strtok_r() functions in C with examples

strtok() and strtok_r() functions in C with examples C offer various strtok() and strtok r() methods for a string to be separated by a certain delimiter. Dividing a string is a...

2 minutes read.

Pi() Function in C

Pi: Mathematic constants are not defined in the c or c++ programming languages. To use the Mathematical constants firstly, we have to define the _USE_MATH_DEFINES and then declare the cmath and...

3 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it shows...

4 minutes read.

Factorial Program in C using For Loop

Before move on the factorial program. We have to know about the for loop in C programming language. The syntax of the For Loop is: for (initialization statement; test expression; an increment...

3 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Bit Stuffing Program in C

What is a Bit Stuffing? The process of inserting one or more extra bits (0) into data is known as bit stuffing. To provide signalling information to a recipient, these are...

3 minutes read.

Commenting in C

Commenting in C Commenting in the C language is used to give out the information about the lines of the code which are included. It is one of the things that...

3 minutes read.

Associativity of Operators in C

What is an Associativity operator? Two operators with equal priority are connected by employing their association when they are present in an expression. There are two different types of associativity: left to rightright...

4 minutes read.

Flow chart of While loop in C

This is a flowchart that represents the process of executing the while loop in the C programming language.Generally, as we know there are three main components of while loop:1. The...

3 minutes read.

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

How to install a C compiler in windows 10-64bit

Many C compilers can be installed on your pc. The most downloaded compilers include GCC, Turbo C++, Visual Studio, etc. This article includes the installation of the Turbo C++ compiler in...

6 minutes read.