C++ Program to Sum the digits of a given number

C++ProgrammingServer Side Programming

Here is an example to calculate the sum of digits in C++ language,

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int x, s = 0;
   cout << "Enter the number : ";
   cin >> x;
   while (x != 0) {
      s = s + x % 10;
      x = x / 10;
   }
   cout << "\nThe sum of the digits : "<< s;
}

Output

Enter the number : 236214828
The sum of the digits : 36

In the above program, two variables x and s are declared and s is initialized with zero. The number is entered by the user and when number is not equal to zero, it will sum up the digits of number.

while (x != 0) {
   s = s + x % 10;
   x = x / 10;
}
raja
Published on 06-Nov-2018 10:31:09
Advertisements