Skip to content

Instantly share code, notes, and snippets.

@HelixSpiral
Created February 8, 2012 03:49
Show Gist options
  • Save HelixSpiral/1765188 to your computer and use it in GitHub Desktop.
Save HelixSpiral/1765188 to your computer and use it in GitHub Desktop.
Returns the sum of the digits to the given number.
/** Write a program that prompts the user for a positive
* integer and then computes the sum of all the digits of
* the number. For example, if the user enters 2784,
* then the program reports 21. If the user enters 59,
* then the program reports 14. The program should work
* for any number having one to ten digits.
*/
#include <iostream>
#include <string>
int main()
{
/* We take a string as input instead of an int because it's easier to handle
a long string of numbers rather than a large number. The max size of an
unsigned int is about 4.2 billion. So we can't have 'numbers' bigger than
that. We can, however, take a string of up to 477,218,588 9's before we
hit 4.2 billion by adding them all up. So we itterate over the string
of numbers and add them to the sum as we go along. */
std::string user_input;
unsigned int sum;
/* User input */
std::cout << "Enter a number: ";
std::cin >> user_input;
/* Loop for all the digits */
for (std::string::iterator x = user_input.begin(); x <= user_input.end(); ++x)
/* This if filters out all the non-numbers. */
if (static_cast<int>(*x) >= 48 && static_cast<int>(*x) <= 57)
sum += (*x - '0');
/* Print the answer */
std::cout << "Sum of the digits is: " << sum << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment