Sum of Digits of a Number in C++ using While loop
ADVERTISEMENTS
Sum of digits of a number in C++ using while loop. In this article, you will learn how to find sum of digits of a number in c++ using while loop.
Sum of Digits of a Number
An integer number of 4 digits is 2468 ==> 2 + 4 + 6 + 8 ==> 20
Source Code
// Sum of Digits of a Number in C++ using While loop
#include <iostream>
using namespace std;
int main() {
int x, sum = 0, m;
cout << "Enter the integer number::\n";
cin >> x;
cout << "The sum of " << x << " digits is = ";
while (x > 0) {
m = x%10;
sum = sum+m;
x = x/10;
}
cout << sum << "\n";
return 0;
}
Output
Enter the integer number::
2468
The sum of 2468 digits is = 20