Click here to Skip to main content
15,891,621 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I was going through some question about recursion . I am having a hard time with recursion .
Here is a question ,we have to evaluate the output of following code :-
VB
On recursion, value of f(513,2)
 
 if(n<0)
   return 0;
 else
   return ( n%10 + f(n/10, 2) )


Now starting with 512

we get return ( 3 + f(51,2)
again we have (3+1+f(5,2)
again (4+5+f(0,2))
we have (4+5+0)

With this i get the result =9 . Is is right ?
Posted
Comments
abbaspirmoradi 31-Aug-13 5:58am    
Correct :
if(n<=0)
return 0;
Member 10200096 31-Aug-13 6:16am    
And what if n<0 . Will it go to infinite loop??
abbaspirmoradi 31-Aug-13 6:23am    
this is clear my friend .n never be negative if your input is positive..

Yes - but the simplest thing to do is try it. Write a simple C function, and call it with your values. See what it does, by following the code execution in the debugger.

To answer your supplementary question, "No" - it will not loop forever if you pass it a negative value, because the test
C++
if (n<0)
terminates execution of the function on a negative value instead of recursing any further.
 
Share this answer
 
Comments
abbaspirmoradi 31-Aug-13 6:39am    
prefect! +5
Probably 9 is right. But the question is not:

1. The first line of the code is not C code - I assume it's part of the textual description or just defines the input.
2. You did not (formally) provide the definition of function f - I assume the last 4 lines of the code describe it. (and I'll silently add that missing ';' at the end)
3. However, f should take 2 arguments, but said code only uses one - the second argument is always constant at value 2! Why is that?

You should work on the accuracy of your descriptions; programming is all about making computers understand your intentions, and none of the above could be accurately guessed by a computer program.

Similarly, if you ask a question about programming, the less accurate your description of the problem, the more likely any answer you get is unusable.
 
Share this answer
 
Comments
nv3 2-Sep-13 8:04am    
I was about to ask the same thing. +5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900