How to add sum of digits without using loops?

Like for all numbers in general with two digits or more
you can't.
you can do it for a subset of numbers, but not all numbers/generally. Consider Pi*10^1000 for example.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <numeric>
using namespace std;

int main()
{
   string number;
   cout << "Enter a number: ";
   cin >> number;
   cout << "Sum of digits is " << accumulate( number.begin(), number.end(), 0, []( int a, char b ) { return a + (b - '0'); } );
}



Alternatively, stay within integer arithmetic and use RECURSION.
Last edited on
> Like for all numbers in general

For all representable integral numbers: use recursion.
1
2
3
4
5
int sum_digits( unsigned long long number )
{
    if( number < 10 ) return number ; // single digit number; return the digit
    else return number%10 /* last digit + sum of the other digits */ + sum_digits( number/10 ) ;
}
Depending on how you define "loop".
To rephrase my initial answer, you can't do it without *iteration* of some form, at least not in any way I know of.

you can do it for a subset of all numbers by unrolling the iteration, and for smallish problems, a direct lookup table.
Last edited on
Topic archived. No new replies allowed.