Problems with understanding how recursion works in C - c

I'm learning about functions in C from the book C Programming: A Modern Approach. It contains the following function:
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
with the following explanation:
To see how recursions works, let's trace the execution of the
statement i = fact(3); here is what happens: "
fact(3) finds that 3 is not equal or less than 1, so it calls
fact(2)which finds that 2 is not equal or less than 1, so it calls
fact(1) which finds that 1 is equal or less than 1, so it returns 1,causing
fact(2) to return 2 x 1 = 2, causing
fact(3) to return 3 x 2 = 6
I'm really confused, why does it does all these actions if it is not inside a loop? why does it keep making the 3 less and less until it matches the argument in if function?
Does the * symbol means that n in the fact(n) is now 3 - 1 and it basically says it do it all over again?

Recursion is the process when a function calls itself.
In the function definition you can see a call to fact(n-1), this means the function itself is called again.
int fact(int n) //return value is an integer, name of function is "fact", input argument is an integer named n
{
if (n <= 1) // if the input arg equals 1, return 1
return 1;
else
return n * fact(n - 1); //else, return n (input arg of this fact) times the return value of fact(n - 1)
}
Fact(3) is supposed to return 3 * 2 * 1 = 6.
What happens when process the statement int a = fact(3) is the following:
fact(3) //dive into this function:
{
if (n <= 1) //n is not 1
return 1;
else
return n * fact(n - 1); //now we call fact(2)
}
we call fact(2):
{
if (n <= 1) //n is not 1
return 1;
else
return n * fact(n - 1); //now we call fact(1)
}
we call fact(1):
{
if (n <= 1) //n equals 1
return 1; //return 1
else
return n * fact(n - 1);
}
Now function fact(1) returns 1 to the point where its called, which is inside fact(2).
To be precise, to the statement return 2*fact(1);, this gets passed back to the statement return 3*fact(2); which gets passed back to our initial function call and our integer 'a' gets the value 6.
I hope this made it more clear to you, if you have still questions left feel free to ask.

Just going by your example to find the factorial of 3
The first call is fact(3)
n = 3 so else condition gets executed
3 * fact(2)
n = 2 so else condition gets executed
2 * fact(1)
n = 1 now if condition passes so it returns 1
So put together
3 * fact(2)
3 * 2 * fact(1)
3 * 2 * 1 = 6
There has to be a exit condition in recursion in this it is
if(n = 1) /* 0! = 1 So you have reached the last iteration and you are good to return */

If you call a function from within itself it's called recursion. Since you return the value
returned from the internal call, the function gets evaluated until it doesn't call itself anymore i.e. when n <= 1, < is just to account for 0! == 1.
It makes 3 or n less and less because of
fact(n - 1) // n - 1 < n

The recursion occurs when fact(n-1) is called. There the function itself is called again, thus the code repeats itself without the need of a loop. The argument value changes because the function is called with a different argument each time.
Btw, the * symbol means a multiplication.

Related

Where do recursive functions end?

#include <stdio.h>
int factorial(int n);
void main()
{
int n;
printf("Enter your number : " );
scanf("%d",&n);
if(n <= 1)
{
printf("The factorial of the number n is ",n);
}
else
{
int res = factorial(n);
printf("The result is %d\n",res);
}
}
int factorial(int n)
{
if(n <= 1)
return 1;
return n * factorial(n-1);
}
I'm doing a recursive function concept for the first time and i pretty much got like a 65% grasp on the concept of recursion. In the above program i have written a factorial recursion function and it goes normally well and i get the output but i'm trying to think where the recursion ends
Like for example i have gave an input of 5 :
The result is 120
but the main thing i wanted is why it doesn't continue after 0, if n <= 1(given if n = 0,-1...and so on during recursion) and then it should keep on returning "1" and multiplying with the recursion function(the factorial function being called inside the "factorial" function).In conclusion I really have no idea where the recursion ends...can you please clear it up.
Lets say you have call factorial(3), then the call-chain will be something like this:
factorial(3) // Initial call
factorial(2);
factorial(1);
return 1; // No more recursion
return 2 * 1; // 1 is the result of factorial(1)
return 3 * 2; // 2 is the result of factorial(2)
The result of factorial(3) will be 6 (3 * (2 * 1)).
In conclusion I really have no idea where the recursion ends..
It ends at the return 1; statement:
int factorial(int n)
{
if(n <= 1)
return 1; <---- Here
return n * factorial(n-1);
}
Maybe it's more clear if you wrote it like:
int factorial(int n)
{
if(n <= 1)
{
// No more recursive calls - just return 1
return 1;
}
else
{
// Do recursive call with decremented argument
return n * factorial(n-1);
}
}
So the code keeps doing recursive calls until n becomes 1. Then it returns 1 to the previous recursive call which returns 2 (2 * 1) to the previous recursive call which returns 6 (3 * 2) to the previous recursive call which returns 24 (4 * 6) .... and so on.
So the final result is calculated like:
1 * 2 * 3 * 4 * ...
\---/
2 * 3
\-------/
6 * 4
\-----------/
24
From Recursion:
In mathematics and computer science, a class of objects or methods exhibits recursive behavior when it can be defined by two properties:
A simple base case (or cases) — a terminating scenario that does not use recursion to produce an answer.
A recursive step — a set of rules that reduces all successive cases toward the base case.
So, terminating scenario('s)/condition('s) is one of property of recursion and it's where the recursion ends.
In context of your program:
Your program is finding the factorial of a given number n.
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n:
n ! = n * ( n − 1 ) * ( n − 2 ) * ( n − 3 ) * ..... * 3 * 2 * 1
which is equivalent to
n ! = n * ( n - 1 ) !
that means, when writing program to calculate the factorial of a number n, we have to calculate the product of all positive integers and stop when reached to 1, which is the terminating condition.
In factorial() function:
int factorial(int n)
{
if(n <= 1)
return 1;
return n * factorial(n-1);
}
The condition if(n <= 1) is the terminating condition for recursive function finding the factorial of n and its where the recursive function factorial() ends.
Additional:
In your program, you are missing the format specifier in this
printf() statement:
printf("The factorial of the number n is ",n);
it should be
printf("The factorial of the number n is %d\n",n);
^^
Note that, 0! is 1 and, after making above change, your program
will give output as 0 when user give input number 0 which is
wrong.
May you should write function to calculate factorial of given positive number n like this:
unsigned int factorial(unsigned int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
and add a check on user input before calling factorial(). This will take care of 0! as well.
Using void as return type of main function is not as per
standards. The return type of main function should be int.
To understand simple recursive code, it helps a lot to draw a diagram (recursive trace). I will draw it in paint, but it's even better to do it on paper. Let's say we are calling factorial(3).
Write down the call of the function. (In the beginning, it's factorial(3))
Ask yourself: "Is the exit condition satisfied?" (In your case the condition is if(n <= 1))
If the answer is yes, check what gets returned and write it under the previous function call, then go to the next step. You have return 1; so 1 gets returned.
If the answer is no, check what gets returned and write it under the previous function call. You have return n*factorial(n-1); so the first time the return value will be 3*factorial(3-1), which is equal to 3*factorial(2). Now go back to step 1) with the new function call and repeat the process until the condition is satisfied. The call here is factorial(2). You can also connect the function calls with arrows to make the diagram more organized.
This is how the diagram should look like when your condition is satisfied:
You now go from the bottom upwards:Write down the value of the very bottom function call, and repeat for every function call above that. In your case, you first write the value of factorial(1), which is 1, then you move up, and you see that factorial(2) is equal to 2*factorial(1). And because you know that factorial(1) is equal to 1, you also know that
factorial(2) is equal to 2.
You can connect the function calls upwards to make the diagram more organized.
You are done. The diagram should look something like this:
With this diagram, we know exactly when the recursion stops - when factorial(1) is called. We also know the end result, which is 6.

tried a example from a c tutorial site kinda got it wrong

I was learning about recursion in C from https://www.tutorialspoint.com/cprogramming/c_recursion.htm and I tried the number factorial example.
#include <stdio.h>
int fact(int i) {
if (i <= 1) {
return 1;
}
return fact(i - 1);
}
int main() {
int i = 3;
printf("numb = %d", fact(i));
return 0;
}
After I executed the code it printed 1. I reviewed the code and found that I forgot to multiply var i with fact(i - 1) at the end of the function. I fixed it and got the correct factorial, but why is fact(3 - 1) equal to 1?
Edit
I had a very shallow understanding of recursion when i posted this question,i thought fact(i-1) would just execute once and didn't get the meaning of calling the function again in the tutorial and i didn't understand it at first when i read the busybee's answer i think i get it now fact(3-1) called fact(2-1) value of var i is now 1 and it satisfied the if condition and returned 1. Another question in the correct version where i multiply var i with fact(i-1) when i change return 1 to return 2 why does it return 12, from the pattern of return 1 and return 2 it seem to multiply 6 result of the function fact with the number in return why? i admit i did no research on what return does and just kinda went with the flow.
To compute the factorial recursively, i must be a positive integer. So that either the value of i is 0 or 1 the factorial will be 1.
If not, then call the recursive factorial algorithm with (i - 1) then multiply the result by i and return that value as shown:
#include <stdio.h>
int fact(int i)
{
if (i ==1)
return 1;
return fact(i - 1) * i; // You forgot to multiply i here
}
int main(void)
{
int i = 3;
printf("Number = %d", fact(i)); // Displaying the factorial of 3
return 0;
}
fact(3 - 1) returns 1 in your first and erroneous version, because it called fact() with i with 2.
This is not less or equal to 1, so fact() is called with 2 - 1. Now this is less or equal to 1, and 1 is returned.
This result is unchanged returned again, and finally once more returned to main().
As a list:
main() calls fact(3).
fact(3) calls fact(2), because its i is 3 and so greater than 1.
fact(2) calls fact(1), because its i is 2 and so greater than 1.
fact(1) returns 1 to fact(2), because its i is less or equal to 1.
fact(2) returns the 1 returned from fact(1) unchanged to fact(3).
fact(3) returns the 1 returned from fact(2) unchanged to main().
main() prints the 1 returned from fact(3).
Edit:
When you're in doubt how your functions are called and what they do, use a debugger (best approach) or insert some printf() (poor man's debugging, but quite easy), like this:
int fact(int i) {
printf("fact(%d) begins ...\n", i);
if (i <= 1) {
printf("... fact(%d) returns 1 because of %d <= 1\n", i, i);
return 1;
}
#if 1 // just temporarily
printf("... fact(%d) calls fact(%d)\n", i, i - 1);
int r = fact(i - 1);
printf("... fact(%d) returns %d\n", i, r);
return r;
#else
return fact(i - 1);
#endif
}
Edit 2:
You might have missed some important things in the lesson on recursive functions.
Each function has its own set of parameters and local variables.
In general, a recursively called function does not have any insight in the local variables or parameters of the calling function.
A recursively called function returns to the calling function. (Some compilers might optimize a "tail call" into a "tail jump", though.)

Question about this recursive program, and how return works

In the function prod(), how does the program ever get past the return 1;, and where is it returning to?
When the program prints "test 1 at the beginning", the value of number is 1, the if statement is true, so it hits the return 1, and shouldn't it terminate there?
Does return not terminate the function?
I understand how the first 4 lines of output work, but I don't know how the code ever reaches the rest of the output. Any help is appreciated and this is just for practice for a future test.
Code below:
#include <stdio.h>
int prod(int number);
int
main(void)
{
int x = 4;
printf("The result of this function call is %d.\n", prod(x));
return 0;
}
int
prod(int number)
{
int p;
printf("test %d at the beginning\n", number);
if (number == 1)
return 1;
p = (number + 1) * prod(number - 1);
printf("test %d at the end\n", number);
return p;
}
You call prod(4) from main. Within prod, you get past the first return since the conditional (4 == 1) is not true (therefore the return statement never gets executed). Then you arrive at p = (4 + 1) * prod(3). prod(3) does something similar: p = (3 + 1) * prod(2). prod(2) sets p = (2 + 1) * prod(1) . Now in prod(1), we hit the conditional (1 == 1) and this is flagged as true, so we enter into its code block, which simply is return 1. In a recursive function such as this, the function that returns, or does not recursively call itself is known as the bottom of the recursive stack (or a leaf in some cases). A return statement loads the context that called (the caller) the currently running function (the callee). In our case, the caller is prod(2). Thus, prod(2)'s p is set to (2+1) * 1 = 3, where 1 is the value just returned. prod(2) then executes the printf and returns its p (which is 3). This is returned to the function that called prod(2), or prod(3). prod(3)'s p then is p = (3 + 1) * 3 (= prod(2) return value) = 12. Thus, prod(3) returns 12 back to prod(4) which is our top level of the recursive stack. prod(4) returns p = (4 + 1) * 12 (= prod(3) return value) = 60. This is returned to main in the context of printf.

Recursive function in C to take 3 to the power of another number

I'm trying to write a recursive function in C to take the value of 3 to the power of another number. For example, if I enter 4, the program will return the value 81. And the following code is the answer for the question. But I can not clearly understand how the code can solve the problem. I mean that when 4 is passed to the function, the first 3 lines in the function body will be ignored, jump straight into the " // This line " . Then how is it from there will the program return the number 81. The function calls itself again with 3 passed? 3*three_power(3) ? I can not clearly understand that. Can someone explain? Sorry because it's a stupid question, I'm new to C.
#include <stdio.h>
int three_power(int power);
int main(){
int a=4;
int b=9;
printf("\n3 to the power of %d is %d", a, three_power(a));
printf("\n3 to the power of %d is %d", b, three_power(b));
return 0;
}
int three_power(int power){
if (power < 1){
return( 1 );
} else
return (3* three_power(power-1)); //This line
}
Yes, it takes the else branch on the first way through, which causes the recursive call for 4 - 1 which again takes the else branch, and so on down to the base case when power is 0 which just returns 1 (since 30 is 1).
The full chain is
3 * three_power(3) =
3 * (3 * three_power(2)) =
3 * (3 * (3 * three_power(1)) =
3 * (3 * (3 * (3 * three_power(0))) =
3 * (3 * (3 * (3 * (1)))) =
3 * 3 * 3 * 3 = 81
It's hard to visualize, but that's it.
You can of course single-step through this in a debugger to get a feeling for it, or just add a printf("power=%d\n", power); to the first line of three_power().
This is the essence of recursion.
In a mathematical sense, you can define the power of 3^n as 3 * 3^(n - 1), right? After all 3 to the anything is 3 multiplied times itself that number of times, right?
The recursion simply says that the answer to "What is 3 to the power?" Well it is 3 times three_power of power minus one. You need only handle the case when power is 0 and the returned value will be multiplied times 3 by the number of recursive calls made.
This is an excellent learning exercise, but you should prefer pow(3, power) because it is more efficient to calculate this way and you don't risk to exceed the maximum recursive call stack.
Consider writing the command flow showing each entry and exit for your example. Also the return on the else is a single line else. I will rewrite it showing the correct brackets.
1e. enter with value 4
2e. enter with value 3
3e. enter with value 2
4e. enter with value 1
5e. enter with value 0
5r. return 1
4r. return 3*5r = 3*1 = 3
3r. return 3*4r = 3*3 = 9
2r. retrun 3*3r = 3*9 = 27
1r. return 3*2r = 3*27 = 81
int three_power(int power)
{
if (power < 1)
{
return( 1 );
}
else
{
return (3* three_power(power-1)); //This line
}
}
Another way of putting it with a single return is
int three_power(int power)
{
int rtnval;
if (power < 1)
{
rtnval = 1;
}
else
{
rtnval = 3* three_power(power-1); //This line
}
return rtnval;
}
This is an example of recursion, which is similar to the mathematical concept of induction. For a given input, is invokes itself on a reduced input, then uses that result to produce the desired result.
A good way to understand how the function works is to start with the simplest case, verify that it works, then move on to the next simplest case, etc.
In this example, the simplest case is when power is 0. In that case, it immediately returns 1. So far so good.
Now consider what happens when power is 1. In this case, it returns 3 * power(0). In other words, it calls itself with a different input, then uses that result to produce a new result. We have already verified that power(0) returns 1. So in this case, it will return 3 * 1, which is just 3. Again, so far so good.
So what happens when power is 2? Well, it returns 3 * power(1). This results in multiple nested calls. We know that power(1) will return 3, so this case will return 9. Again, it's doing what we want.
More generally, when power is >= 1, it recursively calls itself to obtain the result for power - 1. This will in general result in a chain of calls which eventually return the desired result for power - 1. It then multiplies this by 3 and returns the result. This is 3 * (3 ** (power - 1)), which is just 3 ** power as desired.
You can confirm its correctness inductively. The basis case is when power is 0. This case is confirmed directly. Then, assuming it gives the correct result for power - 1, we can see that it will also give the correct result for power, from the recursive step. It will only fail if the result becomes large enough to overflow.
I would propose a more efficient recursion than f(n)=3*f(n-1).
It would be
// f(n) = 1 if n = 0
// f(n) = f(n/2)^2` if n is even
// f(n) = 3*f(n/2)^2 if n is odd
int power3(int n)
{
int m;
if (n == 0)
return 1;
else if (n % 2 == 0)
{
m = power3(n/2);
return m*m;
}
else
{
m = power3(n/2);
return 3*m*m;
}
}
This way the time complexity is reducing from O(n) to O(log(n)).

Working on a Fibonnaci/mysequence code

I was working on a code that is suppose to calculate the sequence:
a(n+2)=-2(n+1)+3a(n) a(0)=2 a(1)= -1
Unfortunately I cannot figure it out. I'm recently new at this (about a month) and I'm going to try best to do this on my own, but I will need some help. Thank you for whoever decides to help me.
#include <stdio.h>
int mysequence(int n)
{
if (n==0) return 2;
if (n==1) return -1;
if (n==2) return 8;
return (2 * mysequence(n+1) + mysequence(n+2))/3;
}
int main()
{
int n;
printf("Enter n = ");
scanf("%d", &n);
printf("%d\n",mysequence(n));
return 0;
}
I'm not sure how you came up with this line:
return (2 * mysequence(n+1) + mysequence(n+2))/3;
But that's not correct. For one thing, mysequence(n) would call mysequence(n+1) (and mysequence(n+2)), which would call mysequence(n+2), which would call mysequence(n+3), which would call mysequence(n+4), etc. - it should be easy to see that you'll never reach mysequence(0) or mysequence(1) (assuming n > 1), thus it would keep going forever, or at least until you run out of memory, since you're increasing instead of decreasing the parameter in subsequent calls.
Let's start from the beginning by first converting this:
a(n+2) = -2a(n+1) + 3a(n)
Into something that looks more like the code: (by subtracting 2 from each n+c)
(on the left side we'd like a(n), since the function takes the parameter n, not n+2)
a(n) = -2a(n-1) + 3a(n-2)
Now we simply need to put that in the code. Replace:
return (2 * mysequence(n+1) + mysequence(n+2))/3;
With
return -2 * mysequence(n-1) + 3 * mysequence(n-2);
Also, you don't really need to specifically cater for n == 2 - it will be handled correctly by the above statement.
The n will be more bigger until unlimited number when run your program.
I think you need change the function to :
a(n)=-2(n-1)+3a(n-2) a(0)=2 a(1)= -1
Replace n+2 with n. It will make n smaller until 1 and 0.
Then code will be:
int mysequence(int n)
{
if (n == 0) return 2;
if (n == 1) return -1;
return (-2 * mysequence(n - 1) + mysequence(n - 2)) / 3;
}
note: n >= 0
Look at the line return (2 * mysequence(n+1) + mysequence(n+2))/3 carefully and compare it with what you know about the sequence:
a(n+2)=-2(n+1)+3a(n).
They have nothing in common.
What you want is return (-2*mysequence(n-1) + 3*mysequence(n-2)).
As to why, well the coefficients should be clear enough, they are just copied from the definition. The reason we call the next level of recursion with n-1 and n-2 is also quite simple, observe:
a(n+2)=-2(n+1)+3a(n) -> substitute n for n-2 -> a(n)=-2(n-1)+3a(n-2).
Your recursive function is infinitely so! The value of n passed in is incremented in the recursive calls, but the base cases for the recursion assume they decrease.
You'll need what is called a change of variables. Let m = n + 2. So n = m - 2. Then the recurrence you've given becomes
a(m) = -2 * (m - 1) + 3 * a(m - 2)
Implement this as a recursive function. Since the value passed as the argument on the right hand side is now less than that the left, the small base case values will be reached for any m >= 0.

Resources