In this Java code example, the checksum of a number is calculated – both iterative and recursive.
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));
}
}
12
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));
}
}
15