// // Example 6.8. Program to add up the digits of a // nonnegative input integer // #include using namespace std; int main() { int readNum(); int findDigitSum(int num); int num; // nonnegative input integer num = readNum(); cout << "The sum of the digits of " << num << " is " << findDigitSum(num) << "." << endl; return 0; } // // Function to print instructions and repeatedly read // integers until the user enters a nonnegative integer, // which the function returns // Pre: none // Post: A nonnegative integer has been read and returned. // int readNum() { int num; // nonnegative input integer cout << "This program returns the sum of the digits" << endl; cout << "of a nonnegative integer." << endl << endl; do { cout << "Enter a nonnegative integer: "; cin >> num; } while (num < 0); return num; } // // Function to return the sum of the digits of a nonnegative // integer // Pre: num is a nonnegative integer. // Post: The function has returned the sum of the // digits of num. // int findDigitSum(int num) { int sum = 0; // sum of digits int rightmostDigit; // rightmost digit of num do { rightmostDigit = num % 10; // extract rightmost digit sum += rightmostDigit; // add digit to ongoing sum num /= 10; // move next digit into rightmost position } while (num > 0); // when num is 0, no more digits to extract return sum; }