recursive functions help please

I am new to C++ and i am trying to create a recursive function that lists each individual digit in an integer and then provides the sum of those digits and ‘sum’ must be a variable that is passed to the function by reference.
I keep getting the error that "invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'" and i think i understand what the error is telling me basically that i am passing a constant number by reference which doesnt work, I just cant figure out how to fix it. Any advice would be appreciated. This is what i got so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int digits(int& sum, int n) {
        if (n<10) return n;
        while (n!=0) {
                sum=0;
                sum +=n%10;
                n = n/10;
        }
        cout << sum;
        while (n!=0) {
                cout << n%10 << " ";
                return digits (n/10);
        }
        cout << endl;
}

int main () {
        int s, n;
        cout << "Input a positive integer";
        cin >> n;
        if (n<=0) return 0;
        digits (s, n);
        return 0;
}
prog.cpp:14:33: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
                 return digits (n/10);
                                 ^
prog.cpp:4:5: error: in passing argument 1 of ‘int digits(int&, int)’
 int digits(int& sum, int n) {
     ^


int digits(int& sum, int n)

The digits function takes two parameters but you're only sending one. And n/10 is an expression that evaluates to a value to be sent. I don't think it has a memory address that the digits function can reference.

return digits (n/10);


Edit: s doesn't get initialized before you send it to the digits function in main.
Last edited on
Topic archived. No new replies allowed.