- C - Home
- C - Overview
- C - Features
- C - History
- C - Standards
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Basic Syntax
- C - User Input
- C - printf Function
- C - Format Specifiers
- Lexical Elements in C
- C - Tokens
- C - Keywords
- C - Identifiers
- Variables and Constants
- C - Variables
- C - Constants
- C - Const Qualifier
- C - Linkage
- Data Types and Type Conversions
- C - Data Types
- C - Literals
- C - Escape Sequences
- C - Booleans
- C - Integer Promotions
- C - Character Arithmetic
- C - Type Conversion
- C - Type Casting
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Unary Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Miscellaneous Operators
- Decision Making & Control Statements
- C - Decision Making
- C - if Statement
- C - if...else Statement
- C - if...else if Ladder
- C - Nested if Statements
- C - Switch Statement
- C - Nested Switch Statements
- C - Switch Case Using Range
- Loops in C
- C - Loops
- C - For Loop
- C - While Loop
- C - Do...while Loop
- C - For Loop vs While Loop
- C - Nested Loop
- C - Infinite Loop
- C - Break Statement
- C - Continue Statement
- C - Goto Statement
- Functions in C
- C - Functions
- C - Function Prototype
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- C - Predefined Identifier __func__
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- C - Dynamic Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Character Arrays
- C - Special Characters
- Pointers in C
- C - Pointers
- C - Initialization of Pointer Arrays
- C - Applications of Pointers
- C - Dereference Pointer
- C - NULL Pointer
- C - void Pointer
- C - Const Pointers & Pointer to Const
- C - Dangling Pointers
- C - Pointer Arithmetics
- C - Pointers and Arrays
- C - Pointer vs Array
- C - Pointer to an Array
- C - Array of Pointers
- C - Pointers vs. Multi-dimensional Arrays
- C - Pointer to Pointer
- C - Chain of Pointers
- C - Character Pointers and Functions
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Array of Function Pointers
- C - Pointers to Structures
- C - Near, Far and Huge Pointers
- C - Restrict Keyword
- User-Defined Data Types
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Dot (.) Operator
- C - Lookup Tables
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Flexible Array Members in Structures
- C - Structures vs Unions
- Memory Management in C
- C - Memory Layout
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- C - Dynamic Array Resizing
- C - Memory Leaks
- File Handling in C
- C - File Handling
- C - Input & Output
- C - File Operations
- C - Formatted Output
- C - getc, getchar, getch, getche
- Preprocessors in C
- C - Preprocessors
- C - Pragmas
- C - Macros
- C - Working of Preprocessor
- C - Preprocessor Operators
- C - Header Files
- C - Custom Header Files
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Cheat Sheet
- C - Useful Resources
- C - Discussion
- C - Online Compiler
Recursion in C
Recursion is the process by which a function calls itself. C language allows writing of such functions which call itself to solve complicated problems by breaking them down into simple and easy problems. These functions are known as recursive functions.
What is a Recursive Function in C?
A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive approach provides a very concise solution to seemingly complex problems.
Syntax
This is how a general recursive function looks like −
void recursive_function(){
recursion(); // function calls itself
}
int main(){
recursive_function();
}
While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
Why Recursion is Used in C?
Recursion is used to perform complex tasks such as tree and graph structure traversals. Popular recursive programming solutions include factorial, binary search, tree traversal, tower of Hanoi, eight queens problem in chess, etc.
A recursive program becomes concise, it is not easily comprehendible. Even if the size of the code may reduce, it needs more resources of the processor, as it involves multiple IO calls to the function.
Factorial Using Recursion
Recursive functions are very useful to solve many mathematical problems such as calculating the factorial of a number, generating Fibonacci series, etc.
The most popular example of recursion is calculation of factorial. Mathematically, a factorial is defined as −
n! = n X (n-1)!
It can be seen that we use factorial itself to define factorial. Hence this is a fit case to write a recursive function. Let us expand the above definition for calculating the factorial value of 5.
5! = 5 X 4! 5 X 4 X 3! 5 X 4 X 3 X 2! 5 X 4 X 3 X 2 X 1! 5 X 4 X 3 X 2 X 1 = 120
While we can perform this calculation using a loop, its recursive function involves successively calling it by decrementing the number till it reaches 1.
Example: Non-Recursive Factorial Function
The following program shows how you can use a non-recursive function to calculate the factorial of a number −
#include <stdio.h>
#include <math.h>
// function declaration
int factorial(int);
int main(){
int a = 5;
int f = factorial(a);
printf("a: %d \n", a);
printf("Factorial of a: %d", f);
}
int factorial(int x){
int i;
int f = 1;
for (i = 5; i >= 1; i--){
f *= i;
}
return f;
}
Output
When you run this code, it will produce the following output −
a: 5 Factorial of a: 120
Example: Recursive Factorial Function
Let us now write a recursive function for calculating the factorial of a given number.
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
#include <math.h>
/* function declaration */
int factorial(int i){
if(i <= 1){
return 1;
}
return i * factorial(i - 1);
}
int main(){
int a = 5;
int f = factorial(a);
printf("a: %d \n", a);
printf("Factorial of a: %d", f);
return 0;
}
Output
Run the code and check its output −
a: 5 Factorial of a: 120
When the main() function calls the factorial() function by passing the variable "a", its value is stored in "i". The factorial() function successively calls itself.
In each call, the value of "i" is multiplied by its earlier value after reducing it by 1, till it reaches 1. As it reaches 1, the product of all the values between the initial value of the argument and 1 is returned to the main() function.
Binary Search Using Recursion
Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in an array.
While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient, especially if the list is too long.
The binary search algorithm checks if the index "start" is greater than the index "end". Based on the value present at the variable "mid", the function is called again to search for the element.
We have a list of numbers arranged in ascending order. Then we find the midpoint of the list and restrict the checking to either left or right of the midpoint, depending on whether the desired number is less than or greater than the number at the midpoint.
Example: Recursive Binary Search
The following code implements the recursive binary searching technique −
#include <stdio.h>
int bSearch(int array[], int start, int end, int element){
if (end >= start){
int mid = start + (end - start ) / 2;
if (array[mid] == element)
return mid;
if (array[mid] > element)
return bSearch(array, start, mid-1, element);
return bSearch(array, mid+1, end, element);
}
return -1;
}
int main(void){
int array[] = {5, 12, 23, 45, 49, 67, 71, 77, 82};
int n = 9;
int element = 67;
int index = bSearch(array, 0, n-1, element);
if(index == -1 ){
printf("Element not found in the array ");
}
else{
printf("Element found at index: %d", index);
}
return 0;
}
Output
Run the code and check its output −
Element found at index: 5
Fibonacci Series Using Recursion
In Fibonacci series, a number is the sum of its previous two numbers. To generate Fibonacci series, the ith number is the addition of i−1 and i−2.
Example
The following example generates the first 10 numbers in the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonacci(int i){
if(i == 0){
return 0;
}
if(i == 1){
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main(){
int i;
for (i = 0; i < 10; i++){
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Output
When the above code is compiled and executed, it produces the following result −
0 1 1 2 3 5 8 13 21 34
Implementing recursion in a program is difficult for beginners. While any iterative process can be converted in a recursive process, not all cases of recursion can be easily expressed iteratively.