15,850,214 members
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
Correct :
if(n<=0)
return 0;
Member 10200096 31-Aug-13 6:16am
And what if n<0 . Will it go to infinite loop??
this is clear my friend .n never be negative if your input is positive..

## Solution 1

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.

prefect! +5

## Solution 2

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.