TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
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
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
test2
void test2(const std::string &text)
Self test 2 - using 8x8 randomly generated key.
Definition
hill_cipher.cpp:505
test1
void test1(const std::string &text)
Self test 1 - using 3x3 randomly generated key.
Definition
hill_cipher.cpp:470
sum_of_digits
int sum_of_digits(int num)
Definition
sum_of_digits.cpp:23
math
sum_of_digits.cpp
Generated by
1.18.0