Sum of Digits at Even and Odd Places using a Loop
One approach is to convert the number to a string, iterate over each digit, and calculate the sum based on whether the digit’s position is even or odd.
<?php
function evenOddDigitSum($num) {
$numStr = (string) $num;
$evenSum = 0;
$oddSum = 0;
for ($i = 0; $i < strlen($numStr); $i++) {
if ($i % 2 == 0) {
$evenSum += $numStr[$i];
} else {
$oddSum += $numStr[$i];
}
}
return ["even" => $evenSum, "odd" => $oddSum];
}
// Driver code
$num = 123456;
$sums = evenOddDigitSum($num);
echo "Even Places Digit Sum: " . $sums["even"] . "\n";
echo "Odd Places Digit Sum: " . $sums["odd"];
?>
Output
Even Places Digit Sum: 9 Odd Places Digit Sum: 12
In this approach, we convert the number to a string to easily access each digit. We then iterate over each digit, checking if its position (index) is even or odd and updating the respective sums.
Sum of Digits at Even and Odd Places in PHP
Given a Number, the task is to sum the Digit of Even and Odd places using PHP. Calculating the sum of digits at even and odd places in a number is a common programming task. Here, we will cover all approaches with detailed explanations and code examples.
Table of Content
- Using a Loop
- Using Mathematical Operations