C Create a function called sumOfSquares that sums the square
C++:
Create a function called sumOfSquares that sums the squares of the digits in an integer passed in (5)
e.g.: 123 = 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14
Solution
SumOfSquares.cpp
#include <iostream>
using namespace std;
int sumOfSquares (int n) ;
int main()
{
int n;
cout << \"Enter an integer: \";
cin >> n;
cout<<\"Sums the squares of the digits in \"<<n<<\" is \"<<sumOfSquares(n)<<endl;
return 0;
}
int sumOfSquares (int n)
{
int sum = 0;
int r = 0;
do {
r = n % 10;
sum += (r * r);
} while ((n = n / 10) != 0);
return sum;
}
Output:
sh-4.3$ g++ -std=c++11 -o main *.cpp
main
sh-4.3$ main
Enter an integer: 123
Sums the squares of the digits in 123 is 14
sh-4.3$ main
Enter an integer: 12345
Sums the squares of the digits in 12345 is 55
