The cross sum (or digit sum) of a number is the sum of its individual digits. For example, the cross sum of 1234
is 1 + 2 + 3 + 4 = 10
. This concept is often used in mathematical algorithms and checksums. In this guide, we will explore two approaches to calculating the cross sum in Java: an iterative approach using loops and a recursive approach using function recursion.
In the iterative approach, we repeatedly extract the last digit of the number using the modulus operator %
, add it to the sum, and remove the last digit using integer division /
until the number becomes zero.
public class CrossSumCalculator {
// Iterative approach to calculate the cross sum
public static int crossSumIterative(int number) {
int sum = 0;
while (number != 0) {
sum += number % 10; // Extract the last digit and add it to sum
number /= 10; // Remove the last digit
}
return sum;
}
public static void main(String[] args) {
int number = 1234;
System.out.println("Cross sum (Iterative) of " + number + " is: " + crossSumIterative(number));
}
}
Cross sum (Iterative) of 1234 is: 10
sum
to 0
.number
is not 0
:number % 10
.sum
.number / 10
.number
becomes 0
, at which point sum
contains the total cross sum.In the recursive approach, we break the problem into smaller subproblems:
number == 0
, return 0
.number % 10
) and add it to the result of the recursive call with number / 10
.public class CrossSumCalculator {
// Recursive approach to calculate the cross sum
public static int crossSumRecursive(int number) {
if (number == 0) {
return 0; // Base case
}
return (number % 10) + crossSumRecursive(number / 10); // Recursive case
}
public static void main(String[] args) {
int number = 1234;
System.out.println("Cross sum (Recursive) of " + number + " is: " + crossSumRecursive(number));
}
}
Cross sum (Recursive) of 1234 is: 10
0
, return 0
(stopping condition).number % 10
.number / 10
(removing the last digit).0
, at which point the accumulated sum is returned.Both iterative and recursive methods effectively calculate the cross sum of a number. The iterative method is more efficient in terms of memory because it does not require extra stack space for recursion. The recursive method, however, provides a more elegant and intuitive way to express the problem. The choice between the two depends on the use case and constraints of your program.