Search code examples
c++ccountsumdigits

Counting the sum of digits in a loop


I have a problem making an algorithm count the sum of digits that were used in a loop.

Let me outline the basic principles :

1 2 3 4 5 6 7 8 9 = 9 Digits
1 2 3 4 5 6 7 8 9 10 = 11 Digits

I have try to search for a solution for a bit, but I could not find a solution that would be suitable.

The base idea is that I have a known number n that will represent the end of the digit count. Count begins from 1 so 1 <= n <= 10000.

The first thing that came to my mind was counting the digit amount:

while(numdig != 0) {
    numDig = n/10;
    digCount++;
}

and continue on with a loop in a loop but I found myself confused on the second loop . After that I thought of a cycle that would use a lot of if`s which would be a very incorrect way of solving the problem.

I hope the problem is understandable.
Thank you


Solution

  • Perhaps this will prove useful (separating the digit counting into its own function) in helping you write your program.

    /* return the number of digits in the number i */
    int ndigits ( int i ) {
        int n = 1;
    
        if (i < 0) i = -i;
        while (i >= 10) { ++n; i /= 10; }
        return n;
    }