1,063 views
1 votes
1 votes

#include <stdio.h>

int f(int n)

    static int r = 0;
    if (n <= 0) return 1;
    r=n;
    return f(n-1) + r;
}

int main() {
    printf("output is %d", f(5));
    return 0;
}

Output obtained was 

output is 6

So does this mean that always return statement is executed left to right and value of static variable r will be the latest value after it has been updated by all recursive calls f(4), f(3), f(2), f(1)? 

However, output is same if I change the return statement as return r + f(n-1); which implies that it always takes latest updated value irrespective of left to right order. Is this assumption correct?

3 Answers

Best answer
1 votes
1 votes

Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Value of return is same for f(n)+r and r+f(n) both, as the value of “r” remains same ie “r=1”.
Top to Down function call:

n r
5 5
4 4
3 3
2 2
1 1

Final Value of “r” is “1”
Return Value:

N r f(n-1) f(n-1)+r
0     1
1 1 1 2
2 1 2 3
3 1 3 4
4 1 4 5
5 1 5 6

This may help:

selected by
1 votes
1 votes
The last but one call i.e f(1) is updating the value of 'r' to 1 and since it's static it's not stored on stack and hence all invocations of the function f have the value of r as 1. Hence

f(1) = f(0) + r // r == 1

       = 2

f(2) = f(1) + r = 2 + 1 = 3

continuing in this way

f(5) = 6

 

You will get 16 as output had a stack variable been there eg. int temp = 0; and set temp = r after r=n;

then write return f(n - 1) + temp;
edited by

Related questions

2 votes
2 votes
3 answers
1
Laahithyaa VS asked Sep 9, 2023
934 views
. What will be the value returned by the following function, when it is called with 11?recur (int num){if ((num / 2)! = 0 ) return (recur (num/2) *10+num%2);else return 1...
1 votes
1 votes
1 answer
4
Himanshu1 asked Dec 31, 2015
782 views