So I recently came upon a problem that required me to add the digits of an integer together and output the sum (ie 111 would equal 1+1+1 = 3). Originally I had attempted a for loop to try and solve this, but could not get it to output anything except 0. I also had an issue with another for loop previously in a similar way. I've already solved the actual problem with a while loop but I can't understand why this didn't work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int digitSum(int n) {
int lengthCount = 0;
int num = n;
int sum = 0;
for (; num != 0; num /= 10, lengthCount++);
for (int i = 1; i <= lengthCount; i++){
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
After the first loop has completed, num will be zero, so there is nothing for the second loop to work upon. Why not do the whole thing in a single for loop (and get rid of lengthCount, it isn't needed).