C++ Code Example: calculate cross sum (iterative and recursive)

In this C++ code example, the checksum of a number is calculated – both iterative and recursive.

Iterative version

#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;
}
Output
12

Recursive version

#include &lt;iostream&gt;
using namespace std;

static int crossSum(int n) {
    return n <= 9 ? n : (n % 10) + crossSum(n / 10);
}

int main() {
    cout << crossSum(994);

    return 0;
}
Output
22