Replacing "+" with "=" when calculating sum of all digits

Hey everyone. I wrote this code in order to successfully determine all the digits of a number as well as the sum. However, here is the output of the code:

2+4+5+11

I want my code to process the following output:

2+4+5=11

Is there any way this can get fixed? Any response would help a lot. Thanks.



#include <iostream>
using namespace std;

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

void listofDigits(int n) {
if (n <= 0) return;
listofDigits(n / 10);
cout << n % 10;
if (n >= 0) cout << "+";
else cout << "=";
}

int main() {
int n = 245;
listofDigits(n);
cout << sumofDigits(n);
}
Last edited on
Have you considered parsing the digits into a container, the processing that, rather that trying to parse and print at the same time?
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
#include <iostream>
#include <stack>
using namespace std;

void sumDigits( int n )
{
   stack<int> S;
   int sum = 0;
   while( n )
   {
      int digit = n % 10;
      S.push( digit );
      sum += digit;
      n /= 10;
   }

   cout << S.top();
   S.pop();
   while ( !S.empty() )
   {
      cout << "+" << S.top();
      S.pop();
   }
   cout << "=" << sum << '\n';
}


int main()
{
   sumDigits( 245 );
}



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

void sumDigits( int n )
{
   string S = to_string( n );
   int sum = 0;
   for ( char c : S )
   {
      cout << ( sum ? "+" :"" ) << c;
      sum += c - '0';
   }
   cout << "=" << sum << '\n';
}


int main()
{
   sumDigits( 245 );
}

Last edited on
Print the '+' with the digit that comes after it, not the one that comes before.
Print the '=' inside main.
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
#include <iostream>
using namespace std;

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

void
listofDigits(int n)
{
    if (n <= 0)
	return;
    listofDigits(n / 10);
    if (n>9) cout << '+';
    cout << n % 10;
}

int
main()
{
    int n = 245;
    listofDigits(n);
    cout << '=' << sumofDigits(n);
}

Topic archived. No new replies allowed.