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
I don't completely like either your version or your teacher's. Your teacher's version does the extra tests that you correctly point out are unnecessary. C's mod operator is not a proper mathematical mod: a negative number mod 10 will produce a negative result (proper mathematical modulus is always non-negative). But since you're squaring it anyway, no difference.
But this is far from obvious, so I would add to your code not the checks of your teacher, but a big comment that explains why it works. E.g.:
/* NOTE: This works for negative values, because the modulus gets squared */
Way back in the 90's. The lecturer had been sprouting on about loops and, long story short, our assignment was to write a function that would return the number of digits for any given integer > 0.
So, for example, the number of digits in 321
would be 3
.
Although the assignment simply said to write a function that returned the number of digits, the expectation was that we would use a loop that divides by 10 until... you get it, as covered by the lecture.
But using loops was not explicitly stated so I: took the log, stripped away the decimals, added 1
and was subsequently lambasted in front of the whole class.
Point is, the purpose of the assignment was to test our understanding of what we had learned during lectures. From the lecture I received I learned the computer teacher was a bit of a jerk (but perhaps a jerk with a plan?)
write a function in C/C++ that returns the sum of the digits of the number squared
I would definitely have provided two answers:
Generally in assignments not all the marks are given just because the code works. You also get marks for making a solution easy to read, efficient and elegant. These things are not always mutually exclusive.
One I can't strees enough is "use meaningful variable names".
In your example it does not make much difference, but if you're working on a project with a milion lines of code readability becomes very important.
Another thing I tend to see with C code is people trying to look clever. Rather than using while(n != 0) I'll show everyone how clever I am by writing while(n) because it means the same thing. Well it does in the compiler you have but as you suggested you teacher's older version has not implemented it the same way.
A common example is referencing an index in an array while incrementing it at the same time ; Numbers[i++] = iPrime;
Now, the next programmer who works on the code has to know if i gets incremented before or after the assignment, just so someone could show off.
A megabyte of disk space is cheaper that a roll of toilet paper, go for clarity rather than trying to save space, your fellow programmers will be happier.