Adon Lamp
Adon Lamp

Reputation: 19

Add the number digits with recursion

I tried to add all the digits in a number but it only adds the first and the last digit. For example 1111 -> 1+1+1+1 = 4 but I got 2, 47879 -> 35 but I got 13, and so on...

Here's the code:

#include <iostream>
using namespace std;
int input(int &n)
{
    cin >> n;
    return 0;
}
int sum(int n, int &s)
{
    int left = n % 10;
    
    if (n < 10)
    {
        return left;
    }
    else
    { 
        s =s+ left + sum( n / 10, s);
    }
}
int main() {
    int n, s = 0;
    input(n);
    sum(n, s);
    cout << s;
}

Also, I can only use recursion; no string, no array, no loop, etc.

Upvotes: 1

Views: 65

Answers (2)

Amin Baqershahi
Amin Baqershahi

Reputation: 401

The function sum have return type of int. But in the recursion path some function calls does not return anything. (if else execute rather than if)

you can simply use this function:

void sum(int n, int &s)
{
    int left = n % 10;

    s += left;

    if (n < 10)
        return;
    else
        sum(n / 10, s);
}

Upvotes: 2

Kostas
Kostas

Reputation: 4176

You can use this much simpler function:

constexpr int sum(int n) {
  return n ? n%10 + sum(n/10) : 0;
}

Or if you want it to be tail-recursive:

int sum(int n, int s = 0) {
  return n ? sum(n/10, s + n%10) : s;
}

In your implementation you never return on the else branch.

Upvotes: 2

Related Questions