In this C++ code example, the checksum of a number is calculated – both iterative and recursive.
#include <iostream>
using namespace std;
static int crossSum(int n) {
int total = 0;
while (0 != n) {
total = total + (n % 10);
n = n / 10;
}
return total;
}
int main() {
cout << crossSum(435);
return 0;
}
12
#include <iostream>
using namespace std;
static int crossSum(int n) {
return n <= 9 ? n : (n % 10) + crossSum(n / 10);
}
int main() {
cout << crossSum(994);
return 0;
}
22