SOURCE FILE: 6.08SumDigits.cpp


//   
// Example 6.8. Program to add up the digits of a    
// nonnegative input integer   
//    
   
#include <iostream.h>
   
int main(void)   
{   
   int ReadNum(void);   
   int FindDigitSum(int);   
   
   int num;             // nonnegative input integer 
   
   num = ReadNum();   
   cout << "The sum of the digits of "     
        << num << " is " <<  FindDigitSum(num) << ".\n";
   
   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(void)   
{   
   int num;             // nonnegative input integer 
   
   cout << "This program returns the sum of the digits\n";
   cout << "of a nonnegative integer.\n\n";
   
   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 
       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;   
}