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
23
int
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
40
void
test1
() {
41
int
test_case_1 =
sum_of_digits
(119765);
42
assert(test_case_1 == 29);
43
}
44
49
void
test2
() {
50
int
test_case_2 =
sum_of_digits
(-12256);
51
assert(test_case_2 == 16);
52
}
53
58
void
test
() {
59
// First test.
60
test1
();
61
// Second test.
62
test2
();
63
}
64
68
int
main
() {
69
test
();
70
std::cout <<
"Success."
<< std::endl;
71
return
0;
72
}
test2
void test2()
Definition
sum_of_digits.cpp:49
test1
void test1()
Definition
sum_of_digits.cpp:40
sum_of_digits
int sum_of_digits(int num)
Definition
sum_of_digits.cpp:23
test
void test()
Definition
sum_of_digits.cpp:58
main
int main()
Definition
sum_of_digits.cpp:68
math
sum_of_digits.cpp
Generated by
1.12.0