×

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

Classification of Programming language

 Classification of Programming language  The programming language represents a set of instructions compiled along with each other to perform a specific task provided by the CPU (Central Processing Unit). A programming...

3 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.

C Program to Find Largest Number Using Dynamic Memory Allocation

This tutorial will teach us how to locate the highest number a user has ever input into a dynamically allocated memory. C Program: #include <stdio.h> #include <stdlib.h> int main ()  {   int no;   double *data_n;   printf...

1 minute read.

Deadlock Detection Program in C

What is Deadlock? A deadlock is a circumstance where a group in the process is halted because they are each holding onto resources while waiting for other methods to obtain them. Think...

5 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

C String Manipulation programs without using Library Functions

C string manipulation programs without using Library Functions The string is the character list, and typically we operate with library functions to read and print the entire string, but here you...

6 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.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Bitwise XOR Operator in C

What is Bitwise? As we know, bits are the smallest unit of a number and are mostly used in a computing system. So, in bitwise, we do operations on bits instead...

3 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Macros in C

In the C programming language, the macro is defined as a segment of the code replaced by the macro defined value at the beginning. ‘#define’ is the directive that defines...

3 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

Pointer in C

Pointer is a variable that is used to contain the address of another variable. We can easily create a pointer in C language. Example: int *ptr Symbol Description & (ampersand sign) Address of an operator...

1 minute read.