Write in C++ a function int sumofdigits( int n ) which computes
and returns the sum of the digits of
n.
Use the following main function to test your code:
int main()
{
int n, sn;
cout << "Enter q to quit or an integer: ";
while ( cin >> n )
{
sn = sumofdigits(n);
cout << "sumofdigits( " << n << " ) = " <<
sn;
cout << "\nEnter q to quit or an integer: ";
}
return 0;
}
Sample output:
Enter q to quit or an integer: 0
sumofdigits( 0 ) = 0
Enter q to quit or an integer: 23
sumofdigits( 23 ) = 5
Enter q to quit or an integer: -345
sumofdigits( -345 ) = 12
Enter q to quit or an integer: 100
sumofdigits( 100 ) = 1
Enter q to quit or an integer: 4
sumofdigits( 4 ) = 4
Enter q to quit or an integer: -345216
sumofdigits( -345216 ) = 21
Enter q to quit or an integer: q
Note: It must compile on its own and have the functions with the correct types and names.
#include <iostream> using namespace std; int sumofdigits(int n) { if (n == 0) return 0; else if (n < 0) return sumofdigits(-1*n); else return (n % 10) + sumofdigits(n/10); } int main() { int n, sn; cout << "Enter q to quit or an integer: "; while (cin >> n) { sn = sumofdigits(n); cout << "sumofdigits( " << n << " ) = " << sn; cout << "\nEnter q to quit or an integer: "; } return 0; }
Get Answers For Free
Most questions answered within 1 hours.