C++ Recursion Code

This is the question:
Your program should:
1. Ask the user for an integer greater than zero.
2. Call a recursive function that calculates the sum of pairs* of digits.
3. Output what those pairs* are and the sum.
*Break up the pairs as follows in these examples: 123 -> 1+23=24, 1234->12+34=46,
12345->1+23+45=69

CAN SOMEONE PLEASE HELP ME?
I have never done programming before

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

int sum(int x) {
   if (x < 10) return x;
   return x % 10 + sum(x / 10);
}

int main() {
   int n;
   cout << "Enter a number greater than 0: ";
   cin >> n;
   cout << "The digit sum is " << sum(n) << endl;
   return 0;
}
You are summing individual digits instead of pairs of digits. Your code is close, you just need to change a single number in three places. Focus on lines 5 and 6.
Ok so I got that part. I just forgot to change it but I saw that.
I am not sure how to approach the print part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int sum(int x) {
        if (x < 100) return x;
        return x%100 + sum(x/100);
}

int main() {
        int n;
        cout << "Please enter a number greater than 0: ";
        cin >> n;
        cout << "The digit sum is " << sum(n) << endl;



return 0;
}
Would I write another function code similar to "sum" but instead it prints or is there an easier way?
I think I got it but I am still missing something

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main() {
        int n;
        cout << "Please enter a number greater than 0: ";
        cin >> n;
        int num=n;
        int s=sum(n);
        int r1=0, r2=0, r3=0;
        
                r1=n/100;
                r2=n%100;
        
        cout << "The sum of the pairs of digits is " << endl;
        cout << num << " -> " << r1 << "+" << r2 << "+" << r3 << "=" << sum(n);
        cout << endl;
return 0;
}

This is the output I am getting

Please enter a number greater than 0: 12345
The sum of the pairs of digits is 
12345 -> 123+45+0=69


But I need this
12345->1+23+45=69
Last edited on
You may find it easier to do the printing from inside your sum function.
I am not sure how to do that, can you direct me a bit
Keep your main function mostly the same - you will only need to print out the = from in main.

In your sum function, print the value that you are summing, and if you are going to recurse, print the plus sign too.
Topic archived. No new replies allowed.