Now that we’ve covered most of the basics, we will be learning to solve different problems. In this lesson, we will think of a solution together to write a program that takes a number and calculates the sum of its digits.

So let’s get to it!

Sum of digits

Write and run a digits summation program (using operators +, %, /) that takes a six-digit integer from the user and prints the sum of its six digits.

Sample Input:

123456

Sample output:

21

Designing the strategy (the algorithm)

To write a program for the above problem, we first focus on the logic which, in this case, is very simple: We remove one digit at a time and add it in a sum variable till all the digits have been added.

For convenience, let’s say we have a variable number, which stores a 3-digit number (we can change it to a 6-digit number later). Also, we have a sum variable, which we initialize to 0. Let’s take the input in the number variable.

Press + to interact
...
int main()
{
int number;
// initializing the sum variable with 0
int sum = 0;
cout << "Enter a 3-digit number: ";
// taking the number from the user
cin >> number;
}
...

Now, how do we separate each digit from the number, and where do we store each digit? Also, how do we get the remaining number each time a digit is removed?

  1. We can create variables to store each digit. For example we can specify int d1, d2, d3. As for how to separate each digit, let’s consider the following:

    Suppose number is 248. What would be the answer to number % 10?

    You got it! It’s 8. We just separated the last digit from the number! We can store this removed digit in variable d1.

  2. Now, after removing a digit, we need to update the number with the number excluding the removed digit before we remove another digit. To see how to do it, let’s consider the following:

    Suppose number is 248. What would be the answer to number = number / 10?

    It’s 24. Haven’t we removed the last digit from the number? Yes!

Now, we can repeat the above two steps to remove each digit. So after removing 8, the number becomes 24, so the answer to number % 10 would be 4. We can store this in d2. Meanwhile, number=number/10 will yield 2, which can be stored in d3.

There we go! We just separated each digit of the number 248. In the end, we can add all separated digits and save the summation in the sum variable. Our code will look like the following:

Press + to interact
int number, d1, d2, d3;
int sum = 0;
cin >> number; // say user enters 248
d3 = number % 10; // d3 = 8
number = number / 10; // number = 24
d2 = number % 10; // d2 = 4
number = number / 10; // number = 2
d1 = number % 10; // d1 = 2
sum = d1 + d2 + d3;
cout << "Sum of the digits is: " << sum << endl;

Implementing the strategy

Now let us implement the strategy discussed above and then improve our implementation incrementally.

Implementation 1: Naive idea

We’ve added the code below.

Instruction: Execute the program line-by-line and see the values inside every digit d1, d2, d3, d4, d5, d6 and how the number variable removes every digit one by one.

#include <iostream>
using namespace std;


int main()
{
   int number, d1, d2, d3, d4, d5, d6;
   int sum = 0;
   cout << "Enter a number containing a 6-digit number: ";
   cin >> number;

   // say number = 123456;
   d6 = number % 10;  // d6 = 6
   number = number / 10; // number = 12345
   
   d5 = number % 10;  // d5 = 5
   number = number / 10;  // number = 1234
   
   d4 = number % 10;  // d4 = 4
   number = number / 10;  // number = 123

   d3 = number % 10;  // d3 = 3
   number = number / 10;  // number = 12

   d2 = number % 10; // d2 = 2
   number = number / 10;  // number = 1

   d1 = number % 10;  // d1 = 1

   sum = d1 + d2 + d3 + d4 + d5 + d6;
   cout << "Sum of the digits is: " << sum << endl;

   return 0;
}





Sum of digits program

The program above runs perfectly fine! You may have noticed that we did not add the line number = number / 10; after line 28. Although we could add it, it’d make no difference. That’s because the number would be 0 at this point.

Now, although we have written the complete program, did you at some point feel that we could have written the code a bit differently? Think in the following direction: Can we avoid making these digits variables d1, d2, d3, d4, d5, and d6? Look at the code and think about how we can avoid making those variables and still solve the problem.

Implementation 2: Saving memory and avoiding the wrong input

If you think carefully, we could have skipped creating all the d1, d2, d3,.. variables altogether. We could just use the sum variable, which is initially 0, and keep accumulating the separated digits directly like this:
sum = sum + number % 10

So the code would be:

Press + to interact
...
...
int number;
int sum = 0;
...
cin >> number; // say user enters 1234
sum = sum + number % 10; // sum = 0 + 4
number = number / 10; // number = 123
sum = sum + number % 10; // sum = 4 + 3
number = number / 10; // number = 12
sum = sum + number % 10; // sum = 7 + 2
number = number / 10; // number = 1
sum = sum + number % 10; // sum = 9 + 1
cout << "Sum of the digits is: " << sum << endl;
...
...

We could also add a condition that would ensure the number entered is not more than 6 digits. Let us add the relevant changes and run the code again:

#include <iostream>
using namespace std;
// Printing the sum of a 6-digit number
int main()
{
    int number;
    int sum = 0;
    cout << "Enter a 6-digit number: ";
    cin >> number;
    if(number > 999999)
    {
        cout << "Invalid input.";
    }
    else
    {
        sum = sum + number % 10;
        number = number / 10;
        sum = sum + number % 10;
        number = number / 10;
        sum = sum + number % 10;
        number = number / 10;
        sum = sum + number % 10;
        number = number / 10;
        sum = sum + number % 10;
        number = number / 10;
        sum = sum + number % 10;
        number = number / 10;
        cout << "sum of 6 digit number is: " << sum << endl;
    }
    return 0;
}



Sum of digits program

We’ve added an if-else condition in lines 10 and 14. Now, if the user enters a number greater than 999999, our program prints Invalid input.

Other than that, did you notice something? Our code from lines 16 to 27 is so repetitive! There are only two lines of code that are repeated for each digit.

Do you think we could still improve our code? Could we use something to perform the same repetitive task in our program?

If you’re thinking of loops, then congratulations on getting the correct answer!

Implementation 3: Improving the program using a loop

We could simply use a loop to write this program. Let’s see how:

#include <iostream>
using namespace std;
// Printing the sum of a 6-digit number
int main()
{
    int number;
    int sum = 0;
    cout << "Enter a 6-digit number: ";
    cin >> number;
    if(number > 999999)
    {
        cout << "Invalid input.";
    }
    else
    {
       int counter = 1;
       while (counter <= 6)
       {
        sum = sum + number % 10;
        number = number / 10;  

        counter++;     
       }
       
        cout << "sum of 6 digit number is: " << sum << endl;
    }
    return 0;
}



Sum of digits program

Notice how our program has been improved and made clean. Our entire sum of digits program can be written in just a few lines with the help of a while or for loop. In line 16, we declare and initialize a variable named counter, which counts the number of times our while loop runs. We keep incrementing the counter by 1 in line 22. The loop’s body is executed as long as counter is less than or equal to 6, which is the total number of our digits.

See the animation below to see how the while loop in the code above works.


With that, we come to the end of our lesson. But we do have a question for you to think about: what if we don’t want a specific digit number and instead want the program to be generic (so that it calculates the sum of any number of digits)?

Instruction: Add your code in the code editor below.

Press + to interact
#include <iostream>
using namespace std;
// Displaying the sum of a n-digit number
int main()
{
int number;
int sum = 0;
cout << "Enter a number: ";
cin >> number;
cout<<number<<'\n';
// Write your code here.
cout << "Sum of the number is: " << sum << endl;
return 0;
}

Enter the input below

Once done, click the “Show Solution” button to see the solution.

We hope you enjoyed this problem solving walk-through. We could have developed an improved solution at the start, but we wanted you to understand why and how loops are helpful for cleaning and improving our code.