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

The code calculates the cross sum of a given integer number n by summing up the individual digits of the number. The cross sum of an integer is defined as the sum of its digits.

For example, the cross sum of 435 is 4 + 3 + 5 = 12.

The code uses a while loop to continuously sum the last digit of the number n until n becomes 0. The last digit is obtained by taking the remainder of n divided by 10, and the n is updated by dividing it by 10 to remove the last digit. This process continues until n becomes 0, at which point the total sum of digits stored in total is returned.

When this code is executed with n = 435, it will output 12, which is the cross sum of 435.

#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

The output of the code will be 18. The crossSum function implements the concept of finding the sum of digits of an integer by using recursion. In this case, the input is 994. The function first checks if the input n is less than or equal to 9, and if so, returns n as the result. If not, the function calculates the sum of the last digit (n % 10) and the sum of the rest of the digits (crossSum(n / 10)), and returns the result. The process continues until n is reduced to a single digit, at which point the function returns that digit as the final result.

#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