Java Code Example: calculate cross sum (iterative and recursive)

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

Iterative version

public class CrossSumIterative {
    static int crossSum(int n) {
        int total = 0;
        while (0 != n) {
            total = total + (n % 10);
            n = n / 10;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.print(crossSum(174));
    }
}
Output
12

Recursive version

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

    public static void main(String[] args) {
        System.out.print(crossSum(915));
    }
}
Output
15