In this Java code example, the checksum of a number is calculated – both iterative and recursive.
This code calculates the cross sum of a given number n
. The cross sum of a number is the sum of its individual digits.
The crossSum
method uses a while loop to keep adding the last digit of n
to total
until n
becomes 0. This is done by using the modulus operator %
to get the last digit of n
, and dividing n
by 10 in each iteration of the loop to remove the last digit.
In the main
method, crossSum
is called with the argument 174
, and the result is printed. The expected output is 12
, since 174
has digits 1
, 7
, and 4
, and the sum of these is 12
.
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
This is a Java program that calculates the cross-sum of an integer using recursion. The cross-sum of a number is the sum of its digits.
The program defines a static method crossSum
that takes an integer n
as its argument. The method uses recursion to sum the digits of the number.
The method checks if n
is less than or equal to 9, in which case it returns n
. This is the base case of the recursion, where the calculation stops.
If n
is not less than or equal to 9, the method returns the last digit of n
(obtained by n % 10
) plus the cross-sum of the rest of n
(obtained by n / 10
).
The main
method calls the crossSum
method with an argument of 915, and prints the result.
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