4,235 views
0 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 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 2 votes

My Answer is

Position:
Show:

Related questions

1 1 vote
0 0 answers
682
682 views
shivamSK asked Jun 19, 2024
682 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("i am here"); }else{ printf("yo...
1 1 vote
1 answers 1 answer
1.4k
1.4k views
abhinowKatore asked Jan 18, 2023
1,432 views
What will be the output of the following program ?answer is 8 but I am getting 5, please explain where I am wrong
2 2 votes
1 answers 1 answer
8.1k
8.1k views
Gangani_Son asked Dec 11, 2018
8,067 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 main(){ int n = ...
2 2 votes
1 1 answer
760
760 views
Akhil01 asked Jul 17, 2016
760 views
#include int main() { int *p, a; p = &a; scanf("%d",p); printf("a = %d *p = %d", a, *p); }a = 32766 *p = 32766a = 32767 *p = 32767a = -1219137971 *p = -1219137971No Outpu...