C++ sum the digits of an integer

int sumOfDigits(int num) { int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } return sum; }

Explanation: 1. Define a function called sumOfDigits that takes an integer parameter num. 2. Initialize a variable sum to 0. 3. Use a while loop to iterate until num becomes 0. 4. Inside the loop, add the last digit of num to sum using the modulo operator % and then remove the last digit from num by dividing it by 10. 5. Return the sum once the loop finishes.