fork download
  1. /*****************************************************************************
  2.  C++ Programming - From Problem Analysis to Program Design 5th Edition
  3.  Chapter 5 - Exercise 1
  4.  
  5.  Write a program that prompts the user to input an integer and then outputs both the individual
  6.  digits of the number and the sum of the digits. For example, it should output the individual
  7.  digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual
  8.  digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and
  9.  output the individual digits of -2345 as 2 3 4 5.
  10.  *****************************************************************************/
  11.  
  12.  
  13. #include <iostream>
  14.  
  15. using namespace std;
  16.  
  17. int main()
  18. {
  19. int inputNumber, sum, individualNumber;
  20. cin >> inputNumber;
  21.  
  22. inputNumber = abs(inputNumber); //Handle negative numbers
  23. sum = 0;
  24.  
  25. do {
  26. individualNumber = inputNumber % 10; //Extract the last digit of the number
  27. sum += individualNumber;
  28. inputNumber = inputNumber / 10; //Remove the last digit
  29. } while (inputNumber > 0);
  30.  
  31. cout << "The sum of the individual numbers is: " << sum << endl;
  32.  
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5504KB
stdin
-12345
stdout
The sum of the individual numbers is: 15