Do I need to explicitly handle negative numbers or zero when summing squared digits?

Summarizing a discussion that’s been percolating in the comments:

  • There is no good reason to test in advance for n == 0. The while(n) test will handle that case perfectly.
  • It’s likely your teacher is still used to earlier times, when the result of % with negative operands was differently defined. On some old systems (including, notably, early Unix on a PDP-11, where Dennis Ritchie originally developed C), the result of a % b was always in the range [0 .. b-1], meaning that -123 % 10 was 7. On such a system, the test in advance for n < 0 would be necessary.

But the second bullet applies only to earlier times. In the current versions of both the C and C++ standards, integer division is defined to truncate towards 0, so it turns out that n % 10 is guaranteed to give you the (possibly negative) last digit of n even when n is negative.

So the answer to the question “What is the meaning of while(n)?” is “Exactly the same as while(n != 0), and the answer to “Will this code work properly for negative as well as positive n?” is “Yes, under any modern, Standards-conforming compiler.” The answer to the question “Then why did the instructor mark it down?” is probably that they’re not aware of a significant language redefinition that happened to C in 1999 and to C++ in 2010 or so.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)