0 votes 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 asked Oct 13, 2017 edited Oct 13, 2017 by kenzou srestha 663 views answer comment Share Follow See all 3 Comments See all 3 3 Comments reply Ashwani Kumar 2 commented Oct 13, 2017 reply Follow Share It should be 240 0 votes 0 votes srestha commented Oct 14, 2017 reply Follow Share can u explain or give reference 0 votes 0 votes smsubham commented Oct 19, 2017 reply Follow Share Wouldn't this result in undefined behaviour? https://gateoverflow.in/60/gate2013-42 0 votes 0 votes Please log in or register to add a comment.
Best answer 2 votes 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 See all 1 1 comment reply srestha commented Oct 14, 2017 reply Follow Share same value taking 2 times rec and f 0 votes 0 votes Please log in or register to add a comment.
3 votes 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 See all 4 4 Comments reply srestha commented Oct 14, 2017 reply Follow Share explain a bit more how getting f value 1 votes 1 votes navya n commented Oct 14, 2017 reply Follow Share always evaluate function from base i.e from f(1) 1 votes 1 votes srestha commented Oct 14, 2017 reply Follow Share thanks:) 0 votes 0 votes saipriyab commented Oct 15, 2017 reply Follow Share 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 votes 0 votes Please log in or register to add a comment.