#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.
Related
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 am trying to find the output for fun(5). But I am getting an unexpected result (19) and don't know why.
My doubt is for n =5 for instance, it would return fun(3) + 3. After that would the return fun(4) + x work or the function fun will be called again?
int fun(int n)
{
static int x = 0;
if (n<=0) return 1;
if (n>3)
{
x = n;
return fun(n-2) + 3;
}
return fun(n-1) + x;
}
This is the sequence of what happens:
call fun(5)
x=0; which, being the initialisation of a static local variable,
only happens before the very first call to fun()
5>3: x=5 (not a problem, static vars can be changed and keep the value)
return fun(3)+3
return fun(2) + 5
return fun(1) + 5
return fun(0) + 5
return 1
return 1 + 5
return 6 + 5
return 11 + 5
return 16 + 3
The exact meaning an relation of the following lines seem to be of interest to you.
static int x = 0;
/* Defines a local but static variable, initialised to 0;
the initialisation happens before the first execution of the function,
conceptually at the beginning of the whole program (credits John Bollinger).
This does NOT cause an assignment to 0 during each execution of the function.
The static attribute also means that the value at the end of one
execution will still be found in the variable at the start of the next
execution, even and especially if that start is before the end of the current execution,
which is typical for recursive functions.
*/
/* ... */
x = n;
/* This conditional (inside an if) assignment in the middle of the
recursive function changes the value of the static variable away from
the initialisation value, to e.g. 5.
If/because no other assignment occurs, the value will stay in the
for the rest of the program.
*/
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 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
I am stuck at the following problem on static/dynamic scoping:
The following program fragment is written in a programming language that allows global
variables and does not allow nested declarations of functions.
global int i = 100, j = 5;
void P(x) {
int i = 10;
print(x + 10);
i = 200;
j = 20;
print (x);
}
main() {P(i + j);}
Q1. If the programming language uses static scoping and call by need
parameter passing mechanism, the values printed by the above program
are
(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105
Q2. If the programming language uses dynamic scoping and call by name
parameter passing mechanism, the values printed by the above program
are
(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105
What I think:
On Q1: As it's static scoping and as per call by need, x should be replaced with i + j. But it will cause a local name conflict as there is already a variable with name i. So it (the global i) might be renamed, lets say to i1, and then call will be:
first call: print(x+10) -> (i1 + j + 10) -> (100 + 5 + 10) -> 115
second call: print(x) -> print(i1 + j) -> 105 (Already evaluated - call by need)
On Q2: In dynamic scoping, you search for a variable in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack.
As per call by name:
print (i1 + j + 10) -> print (100 + 5 +10 ) -> 115
And the second call will be
print(x) -> print(i1 + j) -> (100 + 20) = 120 // Evaluate again - Call be name.
Is this answer correct? (Not present in the options)
Is there something I'm missing? (Dynamic binding may be?)
Q1
OP's answer is correct (D). In fact, because global i is not modified during the execution of P, there is no difference between call by need and call by value.
Here is an example where it does make a difference:
global int i = 100, j = 5;
void IncreaseTheGlobal() {
i = i + 1; // static scoping means this is the GLOBAL i!
print(i);
}
void P(x) {
int i = 10;
IncreaseTheGlobal(); // 101 (increased global i)
print(i); // 10 (local i)
print(x); // 106 (x is evaluated; picks up increased global i)
IncreaseTheGlobal(); // 102 (2nd time increased global i)
print(x); // 106 (x not re-evaluated; unaffected by 2nd increase)
}
main() {
print(i); // 100 (original global i)
P(i + j);
print(i); // 102 (new global i)
}
As already pointed out by OP, the first time x is evaluated, it picks up whatever value global i has at that particular moment. After that initial evaluation, x is no longer affected by a later modification of global i.
Q2
Call by name is typically used in macro languages. So why not use the best known macro language ever: the C preprocessor?
#include <stdio.h>
int i = 100, j = 5;
#define print(num) printf("%d\n", num)
#define P(x) { \
int i = 10; \
print(x + 10); \
i = 200; \
j = 20; \
print(x); \
}
main() {
P(i + j);
}
Compile, run, and see: 25, 220.
Call by name works with a simple search-and-replace; within the body of P, replace every occurrence of x by i + j.
int i = 10;
print(i + j + 10); // 10 + 5 + 10 = 25
i = 200;
j = 20;
print(i + j); // 200 + 20 = 220
In other words, the i and the j inside i + j just pick up the present value of whatever happens to be in scope when x is evaluated.
So the correct answer is B, right? Well, almost... the correct answer depends on the implementation of print.
Suppose print practices call by name too, and print defines its own local variable i, then that would dramatically change the result. Try this:
#define print(num) { int i = 0; printf("%d\n", num); }
The result now changes to 15, 20.
This is probably the most important reason why dynamic scoping is bad for the maintainability of your code. Implementation changes in function print (even something trivial as changing the name of a local variable) might break functions on a higher level.
In the second part that is Call by name
The line i=200 will update the local i
Now while print(x) is called it will be replaced by print(i+j)=>print(200+20)=>220
For Q1:
int i = 10;
print(x + 10); // print (i + j + 10); prints 10 + 5 + 10 = 25; local i gets used here
i = 200;
j = 20;
print (x); // print (i + j); call by need ensures, no reevaluation and i + j is 15.
So, answer is C - 25, 15