How to compute the output for the recursive functions ? I know recursion invokes a stack, but am confusing while solving some aptitude question.
Given the following code snippet:
#include <stdio.h>
void fun(int a){
if(a>0){
fun(--a);
printf("%d ",a);
fun(--a);
printf("%d ",a);
}
return;
}
int main(void){
int num = 5;
fun(num);
return 0;
}
This is not any home work assignment but I am unable to solve such question under exam condition.(Theoretical exam without Compiler)
What is the standard way to solve such question ? Please explain with a small example.Any pointer in the right direction or some web link will be welcomed.
Take a pen and paper; draw the invocations of the function along with the parameters - you'll have a kind of a binary tree. Track the execution and write all relevant data on the page. It will also help you understand the functionality.
The branching involved in recursive invocations (especially binary ones like this one) is very logical and intuitive when you draw it on a paper. This is how I was taught back in school - and imo its a good way of understanding stuff like this, at least at the beginning when not everything is as intuitive.
Example:
fun [5]
/ \
fun[4] fun[3]
/ \ | \
fun[3] fun[2] fun[2] fun[1]
I've drawn the calling tree, the same way you can draw it on the paper. This should help with making whats happening clearer for you. And that's really the way I handled this kind of stuff back in the day, so trust me - it works :)
Writing a recursive method is a bit like making a plan to line up dominoes and knock them over. You have to anticipate how each individual recursive call (domino) is going to add its part to accomplishing the whole task.
That means that the "meat" of a recursive method is not in the recursive part, but in the "end cases" the parts of the code that execute when you are not going to re-call the method, the last domino in the chain, the one that you push to start the fun.
So, let's look at your first example, a recursive program for (integer) division. The division algorithm you are trying to implement is "for positive d and n, let n(0) be n. Keep subtracting d from n(i) step by step, until in some step q, n(q) is less than d. Your answer is q."
The key is to look at the END case first. What if at the start n is already less than d? Then you did "zero steps", so your division result is 0.
In pseudocode:
int divide(int n, int d) {
if (n < d) {
return 0;
}
....
}
Now what if n is not less than d (greater than or equal to d)? Then we want to try another step in the division process with a smaller n. That is, run the divide function again with "the same d" and n = "the old n" - d. But once THAT divide finishes it only tells us how many subtraction steps were required for (n-d)/d. We know that n/d requires one more step. So we have to add that step tally to the result:
int divide(int n, int d) {
if (n < d) {
return 0;
} else {
return divide( n-d, d ) + 1;
}
}
What is that second return actually saying? It says: " I don't know how to compute the result myself, but I do know that it is ONE MORE than the result for 'divide( n-d, d )'. So I will 'pass the buck' to that method call and then just add one to whatever it gives me back."
And the process continues. We keep adding "divide" dominoes to the chain until we reach a divide operation where n has "shrunk" to be smaller than d... our end case, our zero result. Now we knock over the first domino (the last one we added to the chain), returning "0". And the dominoes begin to fall. Every time one domino knocks over another domino we add "1" to the method result until finally the first method call is the last domino to fall, and it returns the division result.
Let's try some examples:
12/18:
divide(12,18)
---> returns 0, since 12 is less than 18
result is 0.
20/5:
divide(20, 5)
---> returns divide(20-5, 5) + 1
------> returns divide(15-5, 5) +1
---------> returns divide(10-5, 5) +1
------------> returns divide(5-5, 5) +1
---------------> returns 0, since 5-5 is 0, which is less than 5
and now the dominoes fall...
------------> returns 0 + 1
---------> returns 1 + 1
------> returns 2 + 1
---> returns 3 + 1
result is 4.
8/3:
divide(8, 3)
---> returns divide(8-3, 3) + 1
------> returns divide(5-3, 3) +1
---------> returns 0, since 5-3 is 2, which is less than 3
and now the dominoes fall...
------> returns 0 + 1
---> returns 1 + 1
result is 2.
You have to be the compiler and computer. Write down the stack as you go:
Enter main, call fun with 5.
In fun, 5 is greater than 0, so
I first decrement 5 to 4, then call fun again
Here if you are writing, I would move to the side and "start a new stack"
I enter fun with 4, which is greater than 0
I decrement 4 to 3, then call fun again
Repeat
I enter fun with 3, which is greater than 0
I decrement 3 to 2, then call fun again
Repeat again
I enter fun with 2, which is greater than 0
I decrement 2 to 1, then call fun again
And once more
I enter fun with 1, which is greater than 0
I decrement 1 to 0, then call fun again
And enter for the last time, this time
I enter fun with 0, which is not greater than 0
I return
Now you go back to where you were:
I enter fun with 1, which is greater than 0
I decrement 1 to 0, then call fun again
I print out 0
On print commands, write that in yet another space, which now only contains "0". continue the function:
I enter fun with 1, which is greater than 0
I decrement 1 to 0, then call fun again
I print out 0
I decrement 0 to -1 and call fun again
Here's another stack, but -1 is not greater than 0, so it does nothing. We go back into the function:
I enter fun with 1, which is greater than 0
I decrement 1 to 0, then call fun again
I print out 0
I decrement 0 to -1 and call fun again
I print out -1
And we finish this stack. We go back to an older stack (we just finished entering fun with 1, so look for the stack that ends with "decrement to 1 and call fun again"):
I enter fun with 2, which is greater than 0
I decrement 2 to 1, then call fun again
I print out 1
I decrement 1 to 0, then call fun again
Calling fun(0) does nothing, so we return and continue:
I enter fun with 2, which is greater than 0
I decrement 2 to 1, then call fun again
I print out 1
I decrement 1 to 0, then call fun again
I print out 0
Then we go to the next oldest stack (we just finished entering fun with 2, so look for the stack that ends with "decrement to 2 and call fun again"):
I enter fun with 3, which is greater than 0
I decrement 3 to 2, then call fun again
I print out 2
I decrement 2 to 1, then call fun again
Here's an important time saver! We've already called fun(1) once before, there's no need to really go through it again. What did fun(1) print out? Look up and you'll see it added "0-1" to the output, so save time and just append that.
This continues until you have finished. It's a lot of work, but writing down your current stacks is the easiest way to complete it. For the sake of trying to keep this already long answer short, the rest is up to you. :)
Add a printf("%d\n", a); at the beginning of the function (outside the if statement) and run the code to see the flow of execution. You can add another parameter to the function that takes the depth of recursion as argument and use it to indent the print statement.
The output of the following program will help you understand the flow of execution.
#include <stdio.h>
void indent(int d)
{
for(int i = 0; i < d; i++)
printf("\t");
}
void fun(int a, int d)
{
indent(d);
printf("function called with a = %d\n", a);
if(a>0)
{
fun(--a, d + 1);
indent(d);
printf("%d\n", a);
fun(--a, d + 1);
indent(d);
printf("%d\n", a);
}
else
{
indent(d);
printf("returning as a<%d> <= 0\n", a);
}
return;
}
int main(void)
{
int num = 5;
fun(num, 0);
return 0;
}
Here is the output:
function called with a = 5
function called with a = 4
function called with a = 3
function called with a = 2
function called with a = 1
function called with a = 0
returning as a<0> <= 0
0
function called with a = -1
returning as a<-1> <= 0
-1
1
function called with a = 0
returning as a<0> <= 0
0
2
function called with a = 1
function called with a = 0
returning as a<0> <= 0
0
function called with a = -1
returning as a<-1> <= 0
-1
1
3
function called with a = 2
function called with a = 1
function called with a = 0
returning as a<0> <= 0
0
function called with a = -1
returning as a<-1> <= 0
-1
1
function called with a = 0
returning as a<0> <= 0
0
2
4
function called with a = 3
function called with a = 2
function called with a = 1
function called with a = 0
returning as a<0> <= 0
0
function called with a = -1
returning as a<-1> <= 0
-1
1
function called with a = 0
returning as a<0> <= 0
0
2
function called with a = 1
function called with a = 0
returning as a<0> <= 0
0
function called with a = -1
returning as a<-1> <= 0
-1
1
3
Tracing recursion can be really fun. Enjoy!
This is kind of a difficult question to answer with only pen and paper, I assume it is to make sure you have understood how the computer does it, especially the two recursive calls to fun.
When simulating the execution on paper, remember that when calling fun recursively, the processor would remember the contents of local variables (here argument a) and which statement to go back to after the called function finishes.
Related
void foo(int n, int sum)
{
int k = 0, j = 0;
if (n == 0) return;
k = n % 10;
j = n / 10;
sum = sum + k;
foo (j, sum);
printf ("%d,", k);
}
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
For me this should be 4,0,2,8,0
However, when i execute it, it gives me 2,0,4,8,0
As the code stands, the argument sum to foo is not really relevant since it is passed by value so the last statement in the main function printf ("%d\n", sum) will print 0 regardless of what happens inside foo. That's the last 0 you see in the output the program generates.
Now, the function foo itself accepts an argument n, performs integer division by 10, and recursively calls itself until n is zero. This in effect means that it will print the decimal digits of the input number which is what you see in the output...
It is called as recursive call to the function.
And internally Recursion run as a stack LAST IN FIRST OUT kind
Now in your case it is first printing the output of last call to foo function
Steps in which your program is executing are like this and result will go in stack
1 - 1 st call to foo value of k = 8
2 - 2 nd call to foo value of k = 4
3 - 3 rd call to foo value of k = 0
4 - 4 th call to foo value of k = 2
And as told earlier it will work like stack so the output of the program will be
2 0 4 8 and if you want 4,0,2,8,0 this as a output you need to write the logic accordingly :)
Yes, the output you are getting is absolutely right.
In main(),foo() is called with a=2048 and sum=0.
In foo() we have n=2048, then the if condition calculates values for k,i.e.,(n%10) and j,i.e.,(n/10) till n becomes equal to 0.
Now since there is a recursive call to foo() with j and sum as parameters, the value of k in each iteration gets pushed to a stack and is popped out when n==0 condition is satisfied.
So, if you trace out the program you get values of k=8,4,0,2 which is pushed to stack in the same sequence and thus while popping the elements we have 2,0,4,8.
I have been going through some exercises from a recommended book I found on this website. I came across this following basic piece of code, which I could not fully understand.
#include <stdio.h>
int main(void)
{
int i;
for (i = 10; i >= 1; i /= 2)
printf("%d ", i++);
return 0;
}
This is my reasoning behind this program fragment:
Variable i is initialised to 10.
i is tested to see if greater or equal to 1, (which is always the case).
The third expression reads: i = i / 2, thus i is divided by 2 and its value stored in i.
In the printf statement i is incremented after each printf statement.
I simply cannot understand why the output of this program is:
1 1 1 1 1 1 1 1 ...
I get that the condition statement is always true, however shouldn't the first values be:
5 3 2 1 1 1 1 1?
Basically I cannot seem to understand why the value of i is straight away being stored as 1. Any corrections regarding my reasoning and/or insight on the matter will be appreciated. Please do excuse the basic nature of this question.
As #abelenky pointed out, the correct output is 10 5 3 2 1 1 1 .... The only mistake you made in your reasoning is that the statement i /= 2 gets evaluated after the body of the for loop, before testing the condition again. Another way to write the same loop would therefore be
for(i = 10; i >= 1; i = (i + 1) / 2)
printf ("%d ", i);
If you are running on Windows, try paging the output through more: myprog | more. This should allow you to see the beginning of the output of this infinite loop. On a linux machine, you could acheive the same result using more or less: myprog | less. Thanks to #EugeneSh for making the suggestion that this could be the issue.
Another way that I have found to view the initial output for programs like this is to hit Ctrl+C immediately after starting the program with Enter. This is not a "standard" method and may require very quick reflexes to get any results for a quick loop like yours.
A final suggestion is to limit the output you produce from the program directly:
int i, count;
for(i = 10, count = 0; i >= 1 && count < 100; i /= 2, count++)
printf("%d ", i++);
This will add a counter that will stop your output after 100 numbers have been printed and allow you to see the first numbers.
On the second line, you have 'i++'.
Thus at each iteration of the loop, it will also increment i by 1.
So supposing i = 1 when you start the loop. First it will be divided by 2 (i /= 2). Since i is an integer, it will become 0. Then, on the second line, you have 'i++', thus incrementing i.
So by the end of the loop iteration, i will be back to being equal to 1 (thus making this loop infinite).
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 working on a program that can convert number to its binary form.
With help, I was able to get this, and it seems to work but I just don't understand how. I guess the best way to do this is to try to explain how I think this is working and someone can correct me.
I have a function that has an if statement that says if n divided by 2 isn't equal to 0 then divide n by 2. Then it prints the remainder if n /2 so either 1 or 0.
The main function just runs the function with whatever number I give it, in this case 456.
But how does the program know to run the function multiple times to get the entire binary form?
I feel like this isn't that complicated but I'm not getting it.
#include <stdio.h>
void ConvertToBinary(int n)
{
if (n / 2 != 0) {
ConvertToBinary(n / 2);
}
printf("%d", n % 2);
}
int main (){
ConvertToBinary (456);
return 0;
}
The function ConvertToBinary is recursive, meaning it calls itself. At some point the function needs to know when to stop calling itself. This is called the base case.
On the first call to this function, n=456. In this case n/2 != 0 is true, so the function calls itself, this time with 228. It keeps calling itself until it gets passed a value where n/2 != 0 is false, which is the base case. The innermost call to the function then prints n % 2 and returns. The next innermost call also prints n % 2 for its value of n, and so on up the call stack.
So the function calls look something like this:
ConvertToBinary(456)
ConvertToBinary(456/2=228)
ConvertToBinary(228/2=114)
ConvertToBinary(114/2=57)
ConvertToBinary(57/2=28)
ConvertToBinary(28/2=14)
ConvertToBinary(14/2=7)
ConvertToBinary(7/2=3)
ConvertToBinary(3/2=1)
print 1%2=1
print 3%2=1
print 7%2=1
print 14%2=0
print 28%2=0
print 57%2=1
print 114%2=0
print 228%2=0
print 456%2=0
Result:
111001000
Step through it line by line on a piece of lined paper. Use indention as you make recursive calls, then unindent as you return. Place the output in the right column of your paper.
I would start with simple numbers like 1, 4, 7, 10, then try 456.
This is my first answer here but I'll try and explain as best I can. This is an example of recursion (Google that) which is a powerful tool for solving certain kinds of problems. The trick is that the method calls itself, so tracing it through (with a smaller example):
1st call
n = 13
call ConvertToBinary with 13 / 2 = 6
2nd call
n = 6;
call ConvertToBinary with 6 / 2 = 3
3rd call
n = 3
call ConvertToBinary with 3 / 2 = 1
4th call
n = 1
1 / 2 = 0 so continue through!
print 1 % 2 = 1
method exits and returns to the 3rd call
3rd call again
print 3 % 2 = 1
method exits and returns to the 2nd call
2nd call again
print 6 % 2 = 0
method exits and returns to the 1st call
1st call again
print 13 % 2 = 1
and done!
Now we have 1101 which is 13 in binary,
#include <stdio.h>
void ConvertToBinary(int n)
{
// is the number passed in 2 or greater? If so, print out the smaller binary digits first.
if (n / 2 != 0) {
// this is a recursive call. It won't return until all the smaller binary digits have been printed.
ConvertToBinary(n / 2);
}
// all the smaller digits have been printed, time to print out the current binary digit.
printf("%d", n % 2);
}
int main (){
ConvertToBinary (456);
return 0;
}
I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn't get it really:
#include<stdio.h>
void count(int);
int main()
{
int x=10,z;
count(x);
}
void count(int m)
{
if(m>0)
count(m-1);
printf("%d",m);
}
When the 1st time count is called with argument as 10. it fulfills the condition and then here starts the recursive part. what happens really when a function calls itself? I don't get it. Please explain with reference to stacks.
While m is greater than 0, we call count. Here is a representation of the stack calls:
count (m = 10)
count (m = 9)
count (m = 8)
count (m = 7)
count (m = 6)
count (m = 5)
count (m = 4)
count (m = 3)
count (m = 2)
count (m = 1)
count (m = 0)
printf 0
printf 1
printf 2
printf 3
printf 4
printf 5
printf 6
printf 7
printf 8
printf 9
printf 10
next time it calls itself it has a smaller value
count(int m)
{
if(m>0)
count(m-1); // now it is calling the method "count" again, except m is one less
printf("%d",m);
}
So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:
if(m>0)
What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)
so you have:
count(int m)
{
if(m>0)
{
count(m-1); // now it is calling the method "count" again, except m is one less
}
printf("%d",m);
}
So, the recursive calls will stop once m is not > 0, and then it will call the printf.
After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....
So the output should be:
"0 1 2 3 4 5 6 7 8 9 10"
EDIT:
In terms of a stack:
This is what the stack is doing:
count(10) // push count(10)
->
count(9) // push count(9)
count (10)
->
...
->
count(0) // push count(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
-> (and then it starts printing and popping the method off the stack)
// pop count(0), and printf(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
// pop count(1), and printf(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
...
->
// pop count(9), and printf(9)
count(10)
->
// pop count(10), and printf(10)
When a function is called the return address (of the next code to execute) is stored on the stack along with its current arguments. Once the function finishes the address and arguments are popped so the cpu will know where to continue its code execution.
Let's write the addresses of the function (for the purpose of this example only)
count(int m)
{
(address = 100) if(m>0)
(address = 101) count(m-1); // now it is calling the method "count" again, except m is one less
(address = 102) printf("%d",m);
}
For m = 1:
The if is fullfield so we execute code at address 101 with m = 1. address 102 and m = 1 are pushed to the stack and the function is executed again from address 100 with m = 0. Since m = 0 we execute address 102 and printing 0 on console. The function ends and the last return address (102) and argument m = 1 are popped and the line at address 102 is executed printing 1 on the screen.
The function count is called with an integer argument of 10.
Since the function argument m which is 10 is greater than 0 the function count calls itself with an integer argument of m which is 10 minus 1 which equals 9.
Step 2 repeats with varying arguments (m-1) until m is not greater than 0 and which point the program prints the value of m.
The recursive function just modifies the parameter given to it and calls itself with that modified value until the desired result is returned (in this case m not being greater than 0).
Each number refers to the line number.
#include<stdio.h>
count(int);
main()
{
1int x=10,z;
2count(x);
}
count(int m)
{
3if(m>0)
4 count(m-1);
5printf("%d",m);
}
The execution happens like this(with x=3) -
line number|value of x
1 3
2 3
3 3
4 2
3 2
4 1
3 1
4 0
5 0
5 1
5 2
5 3
Numbers printed on the screen 0 1 2 3
If you want a more specific answer, then you have to look into how compilers work. But generally speaking the compiler will create machine code for the function that includes a preamble, in this code enough memory is allocated on the stack (by decrementing a stack pointer) that a copy of the functions variables can be placed on the stack (we can store the state of the function).
The function will have values stored in registers and memory and these must be stored on the stack for each (recursive) call, otherwise the new call will overwrite the precious data!. So very basically the machine code looks like this (pseudo code)
//store m on the stack
store m,stack_pntr+m_offset
//put input values in designated register
a0 = m
//allocate memory on the stack
stackPntr -= stack_size_of(count_vars)
//store return address in allocated register
//jump to the first instruction of count
.
.
By changing some data used for computation we can go back and read the same instructions again and get a different result. The abstraction of recursive function allows us to manipulate the data we want to change in a nice "call by value" way so that we don't overwrite it unintentionally.
This is done by the compiler when it stores the state of the calling function on the stack so we don't have to manually store it.