English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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

This is a C ++Language example to calculate the sum of numbers,

Example

#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 result

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 to zero. The number is input by the user, and it will sum the number when the number is not equal to zero.

while (x != 0) {
   s = s + x % 10;
   x = x / 10;
}