Sum of digits program using C++

In this C++ programming guide we will learn how to determine sum of digits using C++ language. Suppose a number 723. So, the sum of digits will be 7 + 2 + 3 = 12. And we will print the integer 12.

We already have discussed about sum of digits in C language. And now you are here to learn C++ programming to determine the sum of digits.

To determine the sum, we will take the number as input from the user. Then we will find the sum of all the digits of that number. Let’s see the program bellow.

C++ program to find sum of digits

Here, we will store the given number inside the variable given_num. Then we will use a loop till given_num > 0 and add the reminder with sum by dividing the number by 10. This well give us the last digit each time. After that we will update the value of given_num by dividing it by 10 again. The source code for C++ is given bellow.

// c++ program to find the sum of digits

#include <iostream>
using namespace std;

int main(){

    int given_num, rem, sum = 0;

    cout << "Enter the integer to find sum of digits : ";
    cin >> given_num;

    while(given_num > 0){
        rem = given_num % 10;
        sum += rem;
        given_num /= 10;
    }

    cout << "\nSum of digits is = " << sum <<endl;

    return 0;
}

Output of this sum of digits program:

sum-of-digits-program-in-c-c-program-to-find-sum-of-digits

Let’s have a look at our C code to determine the sum of digits in C. However you can implement this logic to any programming language to determine the sum of digits.

Previous pagePrime number program

Next pageReverse number