Horje
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.

Approach 1: 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
<?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.

Approach 2: Sum of Digits at Even and Odd Places using Mathematical Operations

Another approach is to extract digits from the number using mathematical operations and then calculate the sums.

PHP
<?php

function evenOddDigitSum($num) {
    $evenSum = 0;
    $oddSum = 0;

    while ($num > 0) {
        $digit = $num % 10;
        if ($digit % 2 == 0) {
            $evenSum += $digit;
        } else {
            $oddSum += $digit;
        }
        $num = (int) ($num / 10);
    }

    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: 12
Odd Places Digit Sum: 9



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to Update Data in MySQL Database Table Using PHP? How to Update Data in MySQL Database Table Using PHP?
How to Break Foreach Loop in PHP? How to Break Foreach Loop in PHP?
How to bold text in PHP? How to bold text in PHP?
PHP Exercises, Practice Questions and Solutions PHP Exercises, Practice Questions and Solutions
How to Set Time Delay in PHP ? How to Set Time Delay in PHP ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15