0 0 votes rec(int x) { static int f; if(x==1) return 1; else f+=x*rec(x-1); return(f); } the value returned by rec(5) is_____________ Programming in C programming-in-c + – srestha 1.5k views answer comment Share Follow Print See all 3 Comments 3 3 Comments reply Ashwani Kumar 2 commented Oct 13, 2017 reply Follow flag It should be 240 0 0 replyShare srestha commented Oct 14, 2017 reply Follow flag can u explain or give reference 0 0 replyShare smsubham commented Oct 19, 2017 reply Follow flag Wouldn't this result in undefined behaviour? https://gateoverflow.in/60/gate2013-42 0 0 replyShare Please log in or register to add a comment.
Best answer 2 2 votes initially f should be initialized to 0 so f=0 function f=f+x*rec(x-1) rec(1)=1 f(2)=0+2*rec(1)=2 f(3)=2+3*rec(2)=8 f(4)=8+4*rec(3)=40 f(5)=40+5*rec(4)=240 s0 f returns 240 navya n answered Oct 14, 2017 • selected Oct 14, 2017 by srestha navya n comment Share Follow See 1 comment 1 1 comment reply srestha commented Oct 14, 2017 reply Follow flag same value taking 2 times rec and f 0 0 replyShare Please log in or register to add a comment.
3 3 votes rec(5)-> f=f+(5*rec(4))=240 rec(4)->f=f+(4*rec(3))=40 rec(3)->f=f+(3*rec(2))=8 rec(2)->f=f+(2*rec(1))=2 rec(1)=1 so answer of rec(5) is 240 saipriyab answered Oct 13, 2017 saipriyab comment Share Follow See all 4 Comments 4 4 Comments reply srestha commented Oct 14, 2017 reply Follow flag explain a bit more how getting f value 1 1 replyShare navya n commented Oct 14, 2017 reply Follow flag always evaluate function from base i.e from f(1) 1 1 replyShare srestha commented Oct 14, 2017 reply Follow flag thanks:) 0 0 replyShare saipriyab commented Oct 15, 2017 reply Follow flag For static variable and global variable default value will be zero and for global variables default value will be garbage value.For static varibale lfe time is through out the program and memory is allocated only once. so initially f=0 rec(1)=1 rec(2)->f=f+(2*rec(1))=0+2*1=2 rec(3)->f=f+(3*rec(2))=2+3*2=8 rec(4)->f=f+(4*rec(3))=8+4*8=40 rec(5)-> f=f+(5*rec(4))=40+5*40=240 0 0 replyShare Please log in or register to add a comment.