What is Recursion | Recursion in “C”
So, hey guys. Today we’ll talk about Recursion in the C program. But before that, if you didn’t read our other topics on C programming then you can visit- C language.
Recursion is a simple but very important feature related to functions in C.
Definition:
Recursion is basically the process of calling a function by itself and the function that called itself is called “ Recursive function”.
Now let’s take an example for better understanding.
#include <stdio.h> int rec(int); //declaraing the recursive function int main() //main function { int a, fact; printf("Enter any number"); scanf("%d",&a); fact = rec(a); printf("Fractional value=%d\n", fact); return 0; } int rec(int x) //recursive function definition { int f; if (x == 1) return (1); else f = x * rec(x - 1); //function is calling itself return (f); }
Now when we enter any number, then as an output, we’ll get the factorial of the entered number as shown below.
Enter any number5 Fractional value=120
Syntax
So, from here we can understand that the syntax of the recursion function is
<returntype><recursive_function> (parameter_list) { statements; ... <recursive_function> (actual_argument); ... }
Let’s understand the recursive function’s part.
Read this following code part carefully
int rec(int x) //recursive function definition where "int x" is the parameter or argument like we did with every function { int f; if (x == 1) return (1); //In these lines we are basically trying to say that if the input is 1 then the output will be also 1 and if the input is any other integer except 1 then the output will be like this- else f = x * rec(x - 1); //Here function is calling itself. We can also write directly return (x * rec(x - 1)); return (f); }
So, I hope you read this properly and understand how the whole thing works.
Types of Recursion
Now, there are two types of recursion.
- Direct recursion: When a function calls itself directly, then it is called a direct recursion. Example: Our previous example is actually a direct recursion.
- Indirect Recursion: When a function uses another function to recall itself then it is called an Indirect recursion.
returntype func1(argument) { ... statements ... return func2(n); } returntype func2(argument) { ... return func1(n); }
So these are all about Recursion in the C language.
Now,
Facts
- Any function, even the main() function can be recursive.
- Recursive programs are slower than non-recursive programs, cause it calls the function, so it needs to save its current state and then call them all again. So this is a disadvantage of the Recursive function.
- As recursive functions have intermediate states, so they required more memory than non-recursive functions. So this is also a disadvantage.
- A recursive function may or may not have a return statement.
If you know more facts about recursion, then you can tell us that in the comment section.
Originally published at https://www.scientyficworld.org on July 15, 2021.