I am not able to understand in how a control paasses from one part to another for example in factorial program using recursion This is the code #include <stdio.h> printf("Enter a Number"); return(f); Here in function,int rec(int x),If a value (Let us suppose 5) passes to x , it is checked whether it is etedqual to one or not as it is not equal to one,else block is executed where f=5*rec(5-1=4) so My question is that when one is subtracted from 5 the value 4 passes to x again and whole program get executed and again 4-1 =3 happens and three is again passed to x so how will multiplication takes place as the number is again again passed to function and stored in x? I am stuck in recursion since two weeks…. Please answer as I Want to move forward in C programming.
#include <stdlib.h>
int rec(int);
int main()
{
int a,fact;
scanf("%d",&a);
fact=rec(a);
printf("Factorial of %d is %d",a,fact);
return 0;
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
}
Let’s go step by step.
As you said, f is f=5*rec(5-1=4). So, now rec(4) will be called and it will return 4*rec(4-1) i.e., 4*rec(3). Thus, the initial expression will become – f = 5*4*rec(3) (as 4*rec(3) is returned from rec(4)). Again, the whole program will run for rec(3) and will return 3*rec(2). Then the expression will become – f = 5*4*3*rec(2). Similarly, rec(2) will be called and will result into 2*rec(1) and making the expression – f = 5*4*3*2*rec(1).
When rec(1) will call the function, the condition of if will get satisfied and simply 1 will be returned and thus making the whole expression – f = 5*4*3*2*1 (1 is returned from rec(1)).
I really like the information you share. I learned a lot of new and useful knowledge from your post. Suika game
Recursion in programming is a technique where a function calls itself to solve smaller instances of the same problem until a base case is reached. In your factorial slice master example, the base case is when the input x is equal to 1, in which case the factorial is 1.