Sum of Single Input in Recursion Function

Lets say I have a single input of the value 5432. I want these values to be added together like this:
 
  5 + 4 + 3 + 2 = 14


What are the different ways you can code this in a recursion function? So far I've thought about populating an array, but I believe it has to be a single input. What I had in mind would require 4 inputs to populate the array.

Another way was to convert string to int but I'm not sure if I could do it due the single input problem.

closed account (LA48b7Xj)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int sum_digits(int n)
{
    if(!n)
        return 0;

    return sum_digits(n/10) + n%10;
}

int main()
{
    cout << sum_digits(5432) << '\n';
}

Last edited on
Topic archived. No new replies allowed.