0% completed
Write a Java program to calculate the sum of digits located at even positions and the sum of digits located at odd positions in a given number. Positions are counted from the right (least significant digit) starting at position 1
. For example, in the number 12345
, the digits at odd positions are 5
, 3
, and 1
, and the digits at even positions are 4
and 2
.
number = 12345
Sum of digits at odd positions: 9
Sum of digits at even positions: 6
5
3
1
5 + 3 + 1 = 9
4
2
4 + 2 = 6
number = 2468
Sum of digits at odd positions: 6
Sum of digits at even positions: 12
8
4
8 + 4 = 12
6
2
6 + 2 = 8
To calculate the sum of digits at even and odd positions in a number, follow these steps:
Initialize Variables:
number
be the input number (of type long
to accommodate large numbers).sumOdd
and sumEven
, to 0
. These will store the sums of digits at odd and even positions, respectively.position
to 1
to keep track of the current digit's position (starting from the right).Handle Negative Numbers:
Iterate Through Each Digit:
while
loop to iterate as long as number
is greater than 0
.digit = number % 10
.position
:
position
is odd, add the digit to sumOdd
.position
is even, add the digit to sumEven
.number
using number = number / 10
.position
by 1
.Display the Results:
sumOdd
and sumEven
.Below is the Java code that demonstrates how to calculate the sum of digits at even and odd positions in a number. This example checks the number 12345
.
.....
.....
.....