Recursive digit addition
Mar 20, 2017 at 9:45pm UTC
Write a recursive function that does the following:
Given a number, add all the digits and display the sum.
Example:
The sum of the number 5432 would be 14.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include<iostream>
using namespace std;
int add (int input, int sum, int temp, int temp2)
{
if (input > 1000 )
{
temp = 1000;
}
else if (input > 100)
{
temp = 100;
}
else if (input > 10)
{
temp = 10;
}
else if (input > 0)
{
temp = 1;
}
sum = input/temp;
temp2 += sum;
input = input - (sum * temp);
add(input, sum, temp, temp2);
cout << temp2;
}
int main()
{
int input = 0;
int sum = 0;
int temp = 0;
int temp2 = 0;
int counter = 4;
cout << "Please input number." << endl;
cin >> input;
add(input, sum, temp, temp2);
}
Every time I run this program recursively it crashes. But if I use a while loop, it works fine. Any help?
Mar 20, 2017 at 10:02pm UTC
Never mind. I got it.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include<iostream>
using namespace std;
int add (int input, int sum, int temp, int temp2)
{
if (input > 1000 )
{
temp = 1000;
}
else if (input > 100)
{
temp = 100;
}
else if (input > 10)
{
temp = 10;
}
else if (input > 0)
{
temp = 1;
}
else
{
cout << temp2;
return 0;
}
sum = input/temp;
temp2 += sum;
input = input - (sum * temp);
add(input, sum, temp, temp2);
}
int main()
{
int input = 0;
int sum = 0;
int temp = 0;
int temp2 = 0;
int counter = 4;
cout << "Please input number." << endl;
cin >> input;
add(input, sum, temp, temp2);
}
Mar 20, 2017 at 10:36pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
using namespace std;
int sumDigits( int n )
{
if ( n < 10 ) return n;
else return sumDigits( n / 10 ) + n % 10;
}
int main()
{
int n;
cout << "Input a positive number: " ; cin >> n;
cout << "Sum of digits is " << sumDigits( n );
}
Input a positive number: 1234567
Sum of digits is 28
Topic archived. No new replies allowed.