Sum of an int with calculation output

Hi. I want to make a program, that sums all the digits of a certain number.
The output should not be just the result. I also want to show, what the computer has done.
So for 1234:
1 + 2 + 3 + 4 = 10
I just wrote a code. This code works only for numbers, that do not or contain a 0. Maybe someone can help me to show the addition of those 0's?
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
#include <iostream>
using namespace std;

int main() {
    int initialnum;
    int total=0;
    int digito;
    int reverse;
    while(cin>>initialnum && initialnum>=0){
        if(initialnum==0){
            cout<<"0 = 0"<<endl;
        }
        else{
        while(initialnum!=0){
            digito = initialnum % 10;
            initialnum /= 10;
            reverse = reverse * 10 + digito;
        }
        while(reverse>0){
            total+=reverse%10;
            cout<<reverse%10;
            if(reverse/10>0){
            cout<<" "<<"+"<<" ";
            }
            reverse/=10;
        }
        cout<<" "<<"="<<" "<<total<<endl;
        total=0;
        }
    }
	return 0;
}
Last edited on
Perhaps an alternative option would be to take in the number as a string, so you can then turn each char into a number and sum those numbers.
yabi, turn on compiler warnings (in GCC, this is -Wall as a minimum).
 In function 'int main()':
17:31: warning: 'reverse' may be used uninitialized in this function [-Wmaybe-uninitialized]
I assume you want to initially set reverse to 0.

Works for me for numbers like 1204. What would you want the output to be for a number like 4000? Do you want it to show the 0s being added, or ignore them?
Last edited on
I want to show those 0's.
So:4 + 0 + 0 + 0 = 4
Last edited on
A bit hackish and brute force on the output, using a C string:
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
// digit sum using C string (char array)

// NO error checking for non-numeric digits entered!

#include <iostream>
#include <cstring>
#include <cstdio>

int digit_sum(char[], int);
void display_digits(char[], int);

int main()
{
   while (true)
   {
      std::cout << "Enter a number to sum (-1 to quit): ";
      int num;
      std::cin >> num;

      if (num < 0) { break; }

      char str_num[20];
      sprintf_s(str_num, 20, "%d", num);
      int size = strlen(str_num);

      display_digits(str_num, size);
   }
}

int digit_sum(char number[], int size)
{
   int sum = 0;

   for (int i = 0; i < size; i++)
   {
      // 'convert' char to number and add to sum
      sum += (number[i] - 48);
   }

   return sum;
}

void display_digits(char number[], int size)
{
   std::cout << number[0];

   if (size > 1) { std::cout << " + "; }

   for (int i = 1; i < size - 1; i++)
   {
      std::cout << number[i] << " + ";
   }

   if (size > 1) {std::cout << number[size -1]; }

   std::cout << " = ";

   std::cout << digit_sum(number, size) << "\n\n";
}


Using C++ std::string, brute force and hackish on output:
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
// digit sum using C++ string

// NO error checking for non-numeric digits entered!

#include <iostream>
#include <string>

int digit_sum(const std::string&);
void display_digits(const std::string&);

int main()
{
   while (true)
   {
      std::cout << "Enter a number to sum (-1 to quit): ";
      std::string str_num;
      std::cin >> str_num;

      if (str_num == "-1") { break; }

      display_digits(str_num);
   }
}

int digit_sum(const std::string& number)
{
   int sum = 0;

   for (int i = 0; i < number.size(); i++)
   {
      // 'convert' char to number and add to sum
      sum += (number[i] - 48);
   }

   return sum;
}

void display_digits(const std::string& number)
{
   int size = number.size();

   std::cout << number[0];

   if (size > 1) { std::cout << " + "; }

   for (int i = 1; i < size - 1; i++)
   {
      std::cout << number[i] << " + ";
   }

   if (size > 1) { std::cout << number[size - 1]; }

   std::cout << " = ";

   std::cout << digit_sum(number) << "\n\n";
}

Enter a number to sum (-1 to quit): 1
1 = 1

Enter a number to sum (-1 to quit): 4000
4 + 0 + 0 + 0 = 4

Enter a number to sum (-1 to quit): -1
You could use std::accumulate to roll over all the values in the string, accumulating a total as you go. The need to output a '+' after every char except the last one means the final one needs special handling so the accumulation should only run as far as the penultimate character:

1
2
3
4
5
6
7
8
9
10
11
12
#include <numeric>
#include <string>
#include <iostream>

int main()
{
	std::string input;
	std::cin >> input;

	int sum = input.back() - '0' + std::accumulate(input.begin(), input.end() - 1, 0, [](int sum, char a) {std::cout << a << " + "; return sum + (a - '0'); });
	std::cout << input.back() << " = " << sum;
}


It might not even need that extra line in it; the following produces the wanted output in at least one place ( http://cpp.sh/5ej6u ) but I do not know off-hand what guarantees we have about the order of evaluation in the cout line:
1
2
3
4
5
6
7
8
9
10
#include <numeric>
#include <string>
#include <iostream>

int main()
{
	std::string input;
	std::cin >> input;
	std::cout << input.back() << " = " << input.back() - '0' + std::accumulate(input.begin(), input.end() - 1, 0, [](int sum, char a) {std::cout << a << " + "; return sum + (a - '0'); });
}
Last edited on
You could use std::accumulate

That would work better than my brute force hacking. The lambda really packs a lot of punch as well.

Your second snippet works fine with Visual Studio.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int sumDigits( int n, string &s )
{
   int d = n % 10;
   s = (char)( '0' + d ) + s;
   if ( n < 10 ) { s = s + " = ";   return n; }
   else          { s = " + " + s;   return d + sumDigits( n / 10, s ); }
}
   
int main()
{
   int n, sum;
   while( true )
   {
      cout << "Enter a number (negative to end): ";   cin >> n;
      if ( n < 0 ) return 0;
      string s;
      sum = sumDigits( n, s );
      cout << s << sum << '\n';
   }
}


Enter a number (negative to end): 1234
1 + 2 + 3 + 4 = 10
Enter a number (negative to end): 4000
4 + 0 + 0 + 0 = 4
Enter a number (negative to end): -1





Or another std::accumulate version:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <numeric>
using namespace std;
   
int main()
{
   string s, text;
   cout << "Number: ";   cin >> s;
   for ( char c : s ) text = text + c + " + ";
   cout << text.substr( 0, text.size() - 2 ) << "= " << accumulate( s.begin(), s.end(), 0 ) - s.size() * '0';
}
Last edited on
Topic archived. No new replies allowed.