title: Do I need to explicitly handle negative numbers or zero when summing squared digits?
body: <p>I recently had a test in my class. One of the problems was the following:</p>
  
  <blockquote>
    <p>Given a number <strong>n</strong>, write a function in C/C++ that returns the sum of the digits of the number <em>squared</em>. (The following is important). The <em>range</em> of <strong>n</strong> is [ -(10^7), 10^7 ]. Example: If <strong>n</strong> = 123, your function should return 14 (1^2 + 2^2 + 3^2 = 14).</p>
  </blockquote>
  
  <p>This is the function that I wrote:</p>
  
  <pre><code>int sum_of_digits_squared(int n) 
  {
      int s = 0, c;
  
      while (n) {
          c = n % 10;
          s += (c * c);
          n /= 10;
      }
  
      return s;
  }
  </code></pre>
  
  <p>Looked right to me. So now the test came back and I found that the teacher didn't give me all the points for a reason that I do not understand. According to him, for my function to be complete, I should've have added the following detail:</p>
  
  <pre><code>int sum_of_digits_squared(int n) 
   {
      int s = 0, c;
  
      if (n == 0) {      //
          return 0;      //
      }                  //
                         // THIS APPARENTLY SHOULD'VE 
      if (n &lt; 0) {       // BEEN IN THE FUNCTION FOR IT
          n = n * (-1);  // TO BE CORRECT
      }                  //
  
      while (n) {
          c = n % 10;
          s += (c * c);
          n /= 10;
      }
  
      return s;
  }
  </code></pre>
  
  <p>The argument for this is that the number <strong>n</strong> is in the range [-(10^7), 10^7], so it can be a negative number. But I don't see where my own version of the function fails. If I understand correctly, the meaning of <code>while(n)</code> is <code>while(n != 0)</code>, <strong>not</strong> <code>while (n &gt; 0)</code>, so in my version of the function the number <strong>n</strong> wouldn't fail to enter the loop. It would work just the same. </p>
  
  <p>Then, I tried both versions of the function on my computer at home and I got exactly the same answers for all the examples that I tried. So, <code>sum_of_digits_squared(-123)</code> is equal to <code>sum_of_digits_squared(123)</code> (which again, is equal to <code>14</code>) (even without the detail that I apparently should've added). Indeed, if I try to print on the screen the digits of the number (from least to greatest in importance), in the <code>123</code> case I get <code>3 2 1</code> and in the <code>-123</code> case I get <code>-3 -2 -1</code> (which is actually kind of interesting). But in this problem it wouldn't matter since we square the digits. </p>
  
  <p>So, who's wrong?</p>
  
  <p><strong>EDIT</strong>: My bad, I forgot to specify and didn't know it was important. The version of C used in our class and tests has to be C99 or <strong>newer</strong>. So I guess (by reading the comments) that my version would get the correct answer in any way.</p>