TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sum_of_digits.cpp
Go to the documentation of this file.
1
7#include <cassert>
8#include <iostream>
9
23int sum_of_digits(int num) {
24 // If num is negative then negative sign is neglected.
25 if (num < 0) {
26 num = -1 * num;
27 }
28 int sum = 0;
29 while (num > 0) {
30 sum = sum + (num % 10);
31 num = num / 10;
32 }
33 return sum;
34}
35
40void test1() {
41 int test_case_1 = sum_of_digits(119765);
42 assert(test_case_1 == 29);
43}
44
49void test2() {
50 int test_case_2 = sum_of_digits(-12256);
51 assert(test_case_2 == 16);
52}
53
58void test() {
59 // First test.
60 test1();
61 // Second test.
62 test2();
63}
64
68int main() {
69 test();
70 std::cout << "Success." << std::endl;
71 return 0;
72}
void test2()
void test1()
int sum_of_digits(int num)
void test()
int main()