Welcome back ,
Today we will learn about Recursion in C programming language and also write a program to understand how it really works.
Recursion is a programming technique where a function calls itself as a subroutine. It can be thought of as a repetitive process in which a function solves a problem by reducing it to smaller sub-problems and calling itself with the smaller sub-problems until the sub-problem is simple enough to be solved directly.
Let us now look at the example below to understand recursion in more better way.
You can copy this code from below :
#include <stdio.h>
int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
int main()
{
int num, result;
printf("Enter an integer: ");
scanf("%d", &num);
result = factorial(num);
printf("The factorial of %d is %d\n", num, result);
return 0;
}
In this example, the function factorial calculates the factorial of a given number n by calling itself with n-1 as the argument until n is 0, at which point it returns 1. The final result is then returned to the calling function, main, which displays the result on the screen.
Thanks to recursion function that helps us to avoid writing code again and again. You simply call the function instead pf writing the entire code again.
Let us look at the output now.
If you also want to learn basics and start your C programming journey then find a teacher today for free on Youtube.
I learnt alot from a teacher who teaches c in hindi and if you are finding someone who teaches in hindi then this person will definitely help you.
I am happy to call myself a trader and small programmer at the same time now.
Happy trading and keep learning what you love.