Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's look at this recursive function in more detail:</p> <pre><code>int sum (int a) { int f; if (a == 0) return f; f = (a% 10) + sum (a/10); } </code></pre> <p>While you're on the right track and you have the right idea in general, your actual implementation is a bit buggy. For starters, let's look at these lines:</p> <pre><code>if (a == 0) return f; </code></pre> <p>You have the right idea to terminate the recursion when <code>a</code> reaches zero, but the way you're doing it is a bit off. In particular, you're returning the value of the integer <code>f</code>, but you've never initialized it. This means that the return value is completely arbitrary. Instead of writing this, I think that you probably meant to write something closer to</p> <pre><code>if (a == 0) return 0; </code></pre> <p>which correctly says "if the number is zero, the sum of its digits is zero."</p> <p>Similarly, take a look at the last line of your function:</p> <pre><code>f = (a% 10) + sum (a/10); </code></pre> <p>Again, your intuition is spot-on: the sum of the digits of a number are given by the sum of its first digit and the sum of the rest of its digits. However, notice that while you're correctly <em>computing</em> the sum of the digits, you aren't correctly <em>returning</em> the sum of the digits. In fact, you don't return anything at all if you execute this code, so the return value from the function is unspecified, hence the garbage output. To fix this, consider rewriting the code like this:</p> <pre><code>return (a % 10) + sum (a / 10); </code></pre> <p>This actually says to hand back the value that you just generated right here, instead of storing it in a local variable that will be immediately cleaned up as soon as the function returns.</p> <p>I believe that the reason you coded this function this way is that you're under the impression that the value of <code>int f;</code> is carried across the function calls. Unfortunately, it is not. When writing a recursive function, each instance of the function is completely independent of each other instance and local variables accessible in one recursive call are not accessible in other recursive calls. Consequently, even though each recursive call has its own variable <code>int f</code>, those variables are all completely independent of one another. The value isn't carried through them. If you want to communicate values across recursive functions, the best way to do it is by using the return value of the recursive calls, or (if you must) by passing a pointer to some value down through the recursion.</p> <p>Hope this helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload