C programming recursion - c

I was into C today and I bumped into this example of using recursive calls and I don't understand how it works. Can someone explain?
#include <stdio.h>
#define SIZE 10
int sample(const int b[], int p); //function prototype
void main(void){
int x;
int a[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
x = sample(a, SIZE); //call
printf("Result is X: %d\n", x);
}
int sample(const int b[], int p){
if (p == 1){
return b[0];
}
else{
return b[p - 1] + sample(b, p - 1); //recursive calls until p is 1
}
}
My question is: Why the output is 55? Does x save the previous value and then add next from next call of the sample? Why the value of x is not just b[0] which is 1?

What might help is to write out a table of the value of p at the first call of sample:
p b[p - 1]
-------- --------
SIZE 10
Since p is not 1, the function sample returns the calculation:
b[SIZE - 1] + sample(b, SIZE - 1)
Or:
10 + sample(b, SIZE - 1)
To calculate sample(b, SIZE - 1), we write out the next value in the table:
p b[p - 1]
-------- --------
SIZE - 1 9
Again, p is not 1, so we ultimately return the following value:
(10 + (9 + sample (b, (SIZE - 1) - 1)))
If you repeat these steps, you can see how this eventually terminates, because we get to a state where p is 1:
(10 + (9 + (8 + ... + (1)))
This results in the answer 55.

The answer is 55 as that's the sum of all 10 terms.
What it's doing is summing the last term with the sum of the others. When presented with the first term it returns that, ending recursion and popping the whole stack.

It happen because when you execute the above code then a memory stack of recursive function call outputs is formed till there is a controlling condition like in this case we have
if (p == 1){
return b[0];
}
so the values you get at every level of recursion are as follows
10 9 8 7 6 5 4 3 2 1
Adding all of them you get 55.
The value of x is not just 1 because the return value of each recursive function calls for decremented values of P is added to calculate the return value of previous call at each call till it reaches 1 (the condition in the parent call).
ie return b[p - 1] + sample(b, p - 1);
For brief explanation refer : http://www.programiz.com/c-programming/c-recursion

Related

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.

How does *(array + 3) work?

I am studying for my midterm. this was an example code
#include <stdio.h>
void doubleArray(int array[], int length)
{
for (int i = 0; i < length-2; i++) {
array[i] += array[i];
}
length += 5;
printf(“%d\n”, length); // Question 29
}
int main(int argc,char *argv[]) {
int integers[6] = { 3, 4, 5, 6, 7, 8};
int length = 6;
printf(“%d\n”, integers[4]); // Question 28
doubleArray(integers, length);
printf(“%d\n”, *(integers + 3)); // Question 30
printf(“%d\n”, *(integers + 4)); // Question 31
printf(“%d\n”, length); // Question 32
}
for questions 30 and 31
the answer is that it prints 12 (30) and 7 (31)
can someone explain to me why and what that "*(integers + 3)" means?
* is a dereference operator on a pointer.
This means that it will "get" the value that's stored at the pointer address of the item right after it ((integers + 3)).
It will interpret this value as the dereferenced type of the item after it (int since (integers + 3) is of type int*)
(integers + 3)
integers is a pointer to the address of the first element of the integers array.
That means that if integers contained [1, 2, 3, 4, 5] then it would point to where 1 is stored in memory.
integers + 3 takes the address of integers (i.e. where 1 is stored in memory) and adds the amount of address space required to store 3 ints (since the pointer is of type int*). Advancing it by one space would give you the address of 2 in memory, advancing it by two spaces would give you the address of 3 in memory, and advancing it by three spaces gives you the address of 4 in memory.
How this applies to your example
(integers + 3) gives you the address of the 4th item in the integers array since it's the first element's address plus the size of three elements.
Dereferencing that with the * operator, gives you the value of the 4th element, 12 (since the value of 6 was doubled by doubleArray)
The same applies to *(integers + 4) except that doubleArray didn't double the 5th element so it gives you 7.
How doubleArray works
for (int i = 0; i < length-2; i++) means start the variable i at 0 and advance it until it is length - 2.
This means it takes the value of everything from 0 to the value of length - 2 but executes the body of the loop for values from 0 to length - 3 since the < is exclusive (the conditional is evaluated BEFORE executing the body of the loop so when i == length - 2 the condition is false and the loop terminates without further execution.
So, for each element, excluding the last two, the element in array is added to itself.

Problems with understanding how recursion works in 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.

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.

Can't decipher the output

#include<stdio.h>
int f(int n)
{
static int a;
if(n)
a=n%10+f(n/10);
return a;
}
int main()
{
printf("%d",f(12345));
}
The output is 15. My doubt is how the stack memory is being used.
Let's pretend to be the computer:
f(12345)
make int a, set to 0 (as static)
a = 12345%10 + f(1234)
note program counter, so we remember where to come back to
f(1234)
a = 1234%10 + f(123)
note program counter, so we remember where to come back to
f(123)
a = 123%10 + f(12)
note program counter, so we remember where to come back to
f(12)
a = 12%10 + f(1)
note program counter, so we remember where to come back to
f(1)
a = 1%10 + f(0)
note program counter, so we remember where to come back to
f(0)
return a, i.e. 0 (since we haven't changed it yet)
return a = 1%10 + 0 = 1
return a = 12%10 + 1 = 3
return a = 123%10 + 3 = 6
return a = 1234%10 + 6 = 10
return a = 12345%10 + 10 = 15
Job done.
You'll get the same result with following function implementation:
int f(int n) {
if (n)
return n%10 + f(n/10);
return 0;
}
In your case behavior will be the same, and that's why. Firstly, when you initialize static int variable, it default value is 0 (unlike to just int declaration inside the function body). Secondly, the only value of n when your function just takes a value and does not assign it is 0, because when the line a=n%10 + f(n/10) evaluated, the recursive f() call happens before assignment to a, and its value remains unchanged before f(0) call.
On every recursive call to f() I denote n and with additional '
so
n = 12345, a = 5
n' = 1234, a' = 4
n'' = 123, a'' = 3
n''' = 12, a''' = 2
n'''' = 1, a'''' = 1
n''''' = 0, a''''' = 0 (because a is static)
the answer is a + a' + a'' + .... = 15
Note: the a doesn't need to be static. int a = 0; will do.
The detailed stack usage is compiler dependent. But we can say roughly that for each call of function f, the "int n" is pushed onto the stack, thus occupying the size of an int.
If you call your function recursively N times, then the stack usage reaches N*sizeof(int) bytes.
You also probably need to add some bytes for the return value as well.

Resources