2,774 views
0 votes
0 votes
Output of this program -
 
int rec(int x)
{
    static int f;
    if(x == 1)
       return(1);
    else  __Y__  ;
    return f ;
}
 
What is the value returned by rec(5)
​a)   when  Y  is     f = f * 1 + rec(x-1) ;
b)    when  Y  is     f = f * x  + rec(x-1) ;

What is proper way to solve this ?

2 Answers

3 votes
3 votes
int rec(int x)
{
    static int f;
    if(x == 1)
       return(1);
    else 
  f = f * 1 + rec(x-1)  ;
     return f ;
}
 
in this 
  f = f * 1 + rec(x-1) ;
is equal to writing f=f+rec(x-1) so f has to be computed when rec(x-1) value is returned to function 
Since f is declared as static so it will be initialized to 0
 
so              rec(5)=8
                                 f=f+rec(4)=4+4
                                 f=f+rec(3)=2+2
                                 f=f+rec(2)=1+1
                                 f=f+rec(1)=0+1   return (rec(1))=1
 
2)
 
int rec(int x)
{
    static int f;
    if(x == 1)
       return(1);
    else 
  f = f * x + rec(x-1)  ;
     return f ;
}
 
in this 
  f = f * x + rec(x-1) ;
here multiplication will be done first and then function will be called ,so returning value of function will not change the result and thus changed value of f  will not reflect.
Since f is declared as static so it will be initialized to 0
 
so              rec(5)=1
                                 f=f*x+rec(4)=0+1
                                 f=f*x+rec(3)=0+1
                                 f=f*x+rec(2)=0+1
                                 f=f*x+rec(1)=0+1   return (rec(1))=1
 
 
 
2 votes
2 votes

My Answer is

Related questions

82
views
0 answers
1 votes
shivamSK asked Jun 19
82 views
#include <stdio.h> void f(int (*x)(int)); int mysh(int); int (*sh)() = mysh; int main() { f(sh); sh++; for(int x=sh;x>=0;x--){ if(x){ printf ... A:10C:10 i will go thereB:10 i will go there number of timesD:10 i will go here number of times
956
views
1 answers
0 votes
abhinowKatore asked Jan 18, 2023
956 views
What will be the output of the following program ?answer is 8 but I am getting 5, please explain where I am wrong
7.5k
views
1 answers
2 votes
Gangani_Son asked Dec 11, 2018
7,488 views
#include <stdio.h> void print(int n, int j){ if (j >= n) return; if (n-j > 0 && n-j >= j) printf("%d %dn", j, n-j); print(n, j+1);} int ... 4(B) 1 72 63 54 4(C) 1 72 63 5(D) 1 23 45 67 8 Answer is B. anyone can explain how?
1.5k
views
2 answers
1 votes
shivam sharma 5 asked Aug 28, 2018
1,459 views
int zap(int n){if (n<=1) then zap =1;else zap = zap(n-3)+zap(n-1);}then the call zap(6) gives the values of zapGive the proper explanation