From de4578c1a47d9c03eb96aa863ed109bec80933f5 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Mon, 15 Jun 2020 22:11:20 +0530 Subject: [PATCH] feat: add sum of digits --- math/sum_of_digits.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 math/sum_of_digits.cpp diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp new file mode 100644 index 000000000..d3e7d3291 --- /dev/null +++ b/math/sum_of_digits.cpp @@ -0,0 +1,28 @@ +/** + * A simple C++ Program to find the Sum of Digits of input integer. + */ +#include + +/** + * Function to find the sum of the digits of an integer. + * @param num The integer. + * @return Sum of the digits of the integer. + */ +int sum_of_digits(int num) { + int sum = 0; + while (num > 0) { + sum = sum + (num % 10); + num = num / 10; + } + return sum; +} + +int main() { + int num; + std::cin >> num; + if (num < 0) { + num = -1 * num; + } + std::cout << sum_of_digits(num); + return 0; +} \ No newline at end of file