I have the following recursive function
#include <stdio.h>
#include <string.h>
int mult(int a, int b);
int main()
{
printf("mul: %d\n", mult(5,4));
}
int mult(int a, int b){
if(b==0){
return 0;
}else{
return a +mult(a, b-1);
}
}
In the function there are two return statements. As of my understanding a return statement either terminate the program or return the value that is present next to it in the return statement.
Here whatever happens at the end the value of b becomes zero eventually and the condition b==0 satisfies and return 0 statement get executed. So now the function mult return value should be zero. But it is giving the exact answer i.e multiplication.
when I change return value say 10 this 10 is getting added to the answer.
let us say i gave mult(5,4) the answer is 20 if return value in b==0 condition is zero
the answer is 21 if return value in b==0 condition is 1
the answer is 30 if return value in b==0 condition is 10
and so on..
So whats happening is whatever the return value is else statement it getting added to the return value in if statement.
Can someone explain this why this is happening why the function is returning correct value but it supposed to return 0 since it is the last statement getting executed.your text
I suggest you draw out all the calls to mult using pen and paper. Write down the actual values being passed to the function calls, write down what each will return.
For this time I'll show it done, but next time please do it yourself.
We start with mult(5, 4). It will return 5 + mult(5, 3).
The call mult(5, 3) will return 5 + mult(5, 2).
The call mult(5, 2) will return 5 + mult(5, 1).
The call mult(5, 1) will return 5 + mult(5, 0).
The call mult(5, 0) will return 0.
Now we go back up the call stack:
5 + mult(5, 0) is the same as 5 + 0 which is 5.
5 + mult(5, 1) is the same as 5 + 5 which is 10.
5 + mult(5, 2) is the same as 5 + 10 which is 15.
5 + mult(5, 3) is the same as 5 + 15 which is 20.
So mult(5, 4) will return 20.
Related
This question already has answers here:
Checking return value of a function without return statement
(3 answers)
Closed last month.
`
#include <stdio.h>
int k = 0;
int factorial (int x)
{
if (x == 1)
{
return 1;
}
k = x * factorial (x - 1);
}
int main()
{
printf ("Factorial of %d is: %d\r\n", 5, factorial(5));
return 0;
}
Factorial of 5 is: 120
I have been learning recursion for the last few days, and while working on the factorial of a given number using recursion, everything works fine, but the question I am having is that the above code, without any return statement, is printing the value 120 in the console for the factorial of 5.
Also, I am curious to know how, without any return statement except in the base condition of the factorial function, the recursive call is giving the correct answer.
if (x == 1)
{
return 1;
}
k = x * factorial (x - 1);
As per my understanding, the above line of code would execute like this:
k = 5 * factorial (5-1)
k = 4 * factorial (4-1)
k = 3 * factorial (3-1)
k = 2 * factorial (2-1)
k = 1 * factorial (1-1)
return 1; --> when x is 1
What value it will have in the factorial (x - 1) is something I don't understand. Because this factorial (x) function does not have any return statements.
If a function is defined to return a value but doesn't, and if an attempt is made to use the return value, this triggers undefined behavior in your program.
One of the ways undefined behavior can manifest itself is that the program appears to work properly. There is however no guarantee of this result, and in fact making seemingly unrelated changes to your code can change how undefined behavior can manifest itself.
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.)
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.
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)).
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.