C++ FAQ - How to add the individual digits of a given number?
To solve this problem, you need to do mod (modulus %) and division (/) operations in a for loop until you reach single digit.
Look at the sample code and output! It is easy to understand.
Source Code
#include <iostream>
#include <tchar.h>
// Adding the individual digits of a given number
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
int input = 0;
std::cout << "\nEnter a number (-1 to exit): ";
std::cin >> input;
if( input < 0)
break;
int sum = 0;
int j = 0;
for(; input >= 10; j++)
{
sum += input % 10;
input = (input / 10);
}
sum += input;
j++;
std::cout << "Number of digits: " << j;
std::cout << "\tSum of digits: " << sum;
std::cout << "\n\n";
}
return 0;
}
Output
Enter a number (-1 to exit): 100
Number of digits: 3 Sum of digits: 1
Enter a number (-1 to exit): 123
Number of digits: 3 Sum of digits: 6
Enter a number (-1 to exit): 555
Number of digits: 3 Sum of digits: 15
Enter a number (-1 to exit): 6666
Number of digits: 4 Sum of digits: 24
Enter a number (-1 to exit): 88888
Number of digits: 5 Sum of digits: 40
Enter a number (-1 to exit): -1
|