I recently had a test in my class. One of the problems was the following:
Given a number n, write a function in C/C++ that returns the su
As others have pointed out, the special treatment for n==0 is nonsense, since for every serious C programmer it is obvious that "while(n)" does the job.
The behaviour for n<0 is not that obvious, that's why I would prefer to see those 2 lines of code:
if (n < 0)
n = -n;
or at least a comment:
// don't worry, works for n < 0 as well
Honestly, at what time did you start considering that n might be negative? When writing the code or when reading your teacher's remarks?