C++ Program to Find the Sum of the digits of a given number (3 Ways)

In this program, we will discuss how to find the sum of the digits of a number using the python C++ language.

For example -
The number is 15423.
And the sum is 15.

We will discuss three ways to write the C++ program for it.

  1. By using the while loop.
  2. By using string.
  3. And by using recursion.

Let's discuss these ways one by one.

C++ Programming Code to Find the Sum of the digits of a given number

By using the loop (while loop)

In this method, we use the while loop to get the individual digit from the number, so that we can add them and store it in sum variable.

Here, we take the remainder of the number by dividing it by 10 then change the number to the number with removing the digit present at the unit place. We repeat this process in the while loop. And in every iteration, we sum up the remainder till the number becomes 0.

Code:-

#include<iostream>

using namespace std;

int main() {
   int num, sum = 0;

   cout << "Enter the number : ";
   cin >> num;

   while (num != 0) {
      sum = sum + num % 10;
      num = num / 10;
   }

   cout << "The sum of the digits: "<< sum << endl;
}

Output:-

Enter the number : 512548
The sum of the digits: 25

By using string

In this program, we will store the number in string. And then with help of for loop traverse through every character in the string and convert that character to int so that we can add up the digits and store it in sum variable.

Code:-

#include<iostream>

using namespace std;

int main() {
    string num;
    int sum = 0;

    cout << "Enter the number : ";
    cin >> num;

    for(int i=0;i<num.size();i++){
        sum += (num[i] - '0');
    }

    cout << "The sum of the digits: "<< sum << endl;

    return 0;
}

Output:-

Enter the number : 345
The sum of the digits: 12

By using recursion

In this, we will define a recursive function getDigitSum(). This function will return the sum of the digits.

Code:-

#include<iostream>

using namespace std;

int getDigitSum(int num) {

    if(num == 0){
        return 0;
    }else{
        return num%10 + getDigitSum(num/10);
    }
}

int main() {
   int num, sum = 0;

   cout << "Enter the number : ";
   cin >> num;

   cout << "The sum of the digits: "<< getDigitSum(num) << endl;
}

Output:-

Enter the number : 561495
The sum of the digits: 30

You can learn about many other C++ Programs Here.







The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...