-2

So I made a function that when I put in a set of integers it will display its result example (1234 = 10) but I wasn't allowed to do it with using recursion,

I'm just kind of lost on how to do it without recursion its probably simple but I cant see it.

This is my original code I'm using C++:

#include <iostream>

using namespace std;

int sumofdigits(int n) {
    if (n < 10) return n;
    return n % 10 + sumofdigits(n / 10);
}

int main() {
    int number;
    while (true) {
        cout << "Please, enter numbers (0 to exit): ";
        cin >> number;
        if (!number) break;
        cout << "your result is " << sumofdigits(number) << endl;
    }
    return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
jsch64
  • 13
  • 3

2 Answers2

2

Here's the equivalent using loops:

unsigned int sum_of_digits(unsigned int value)
{
  unsigned int sum = 0U;
  while (value > 0)
  {
    sum = sum + value % 10;
    value = value / 10;
  }
  return sum;
}

Edit 1: Using characters
For some of these assignments, the number is best kept as a string of numeric characters. This allows the program to handle numbers that are too big to fit into an int, long int or long long type.

unsigned int sum_of_digits(const std::string& number)
{
  unsigned int sum = 0U;
  const unsigned int length = number.length();
  for (unsigned int i = 0U; i < length; i++)
  {
    unsigned int digit = number[i] - '0'; // Convert from character to number.
    sum += digit;
  }
  return sum;
}

Note: This solution may be faster because it does not use the division function, which may be an expensive operation on some platforms.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

You would need to use a loop:

int sumofdigits(int n) {
    // will hold the sum at the end of the loop
    int sum = 0;
    while(n>0) {
        sum += n%10; // add current digit
        n /= 10; // drop the digit we just added
    }
    return sum;
}

So with the input n=1234, the loop will go through the following steps:

sum=0, n=1234
sum=4, n=123
sum=4+3, n=12
sum=4+3+2, n=1
sum=4+3+2+1, n=0
Exit the loop when n=0
jadhachem
  • 1,123
  • 2
  • 11
  • 19