For loop madness

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;
}
closed account (48T7M4Gy)
What is line 7 doing?
Line 7 is keeping count of how many digits are in the number to tell the second loop how many times to iterate.
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).
closed account (48T7M4Gy)
OK

By the look of it lines 9 and 10 are using a value of num = 0. Better use n instead.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    int n = 1234;
    int sum = 0;
  
  while(n != 0)
  {
      sum += n % 10;
      n /= 10;
  }
  
  std::cout << sum << '\n';
  return 0;
}
Topic archived. No new replies allowed.