Example 8: Even/Odd Loop

Modulo operator and conditional processing in loops

Download file bucle

🎯 Live Demo

Number Analysis (0-50)

🔵
26
Even Numbers
51%
🔴
25
Odd Numbers
49%
🧮
625
Sum of Odds
Average: 25

📋 Latest Evens:

36, 38, 40, 42, 44, 46, 48, 50

📋 Latest Odds:

35, 37, 39, 41, 43, 45, 47, 49

Change the analysis limit!

We will analyze numbers from 0 up to this limit

Quick limits:

🔢 Real-Time Calculation:

📖 Code Explanation

Complete PHP Code

<?php
$numero = 50;
$suma = 0;

for ($i = 0; $i <= $numero; $i++) {
    if ($i % 2 == 0) {
        print($i);
    } else {
        $suma += $i;
    }
}

print("La suma total de impares es: \$suma");
?>

📝 Lines 1-2: Initial variables

$numero = 50;
$suma = 0;

What does it do? Defines the analysis limit and initializes the accumulator variable.

Why is it done this way? $suma must start at 0 in order to accumulate values correctly.

💡 Concept: Accumulator variables

Variables like $suma are used to accumulate values during a loop. They must be initialized before the loop.

📝 Line 4: Loop for

for ($i = 0; $i <= $numero; $i++) {

What does it do? Creates a loop that goes through all numbers from 0 up to the limit.

Why is it done this way? for loop is perfect for traversing known numeric ranges.

💡 Concept: Inclusive range

We use <= instead of < to include the limit number in the analysis.

📝 Lines 5-9: Condition with modulo operator

if ($i % 2 == 0) {
print($i);
} else {
$suma += $i;
}

What does it do? Uses the modulo operator to determine whether a number is even or odd.

Why is it done this way? The % operator returns the remainder of a division, perfect for checking parity.

💡 Concept: Modulo operator (%)

$i % 2 returns 0 if $i is even, 1 if it's odd. It's the most efficient way to check parity.

📝 Compound assignment operator

$suma += $i;

What does it do? Equivalent to $suma = $suma + $i. Accumulates the current value into the total sum.

Why is it done this way? More compact and readable than the expanded form.

💡 Concept: Compound operators

+= adds and assigns
-= subtracts and assigns
*= multiplies and assigns
/= divides and assigns

➗ Modulo Operator in Depth

What is the modulo operator?

The % operator returns the remainder of a division between two numbers.

10 % 3 = 1 (10 ÷ 3 = 3 with remainder 1)
15 % 5 = 0 (15 ÷ 5 = 3 exact)
7 % 2 = 1 (7 ÷ 2 = 3 with remainder 1 → odd)
8 % 2 = 0 (8 ÷ 2 = 4 exact → even)

Common uses of modulo

🔍 Check parity

if ($numero % 2 == 0)

Determines whether a number is even or odd

🔄 Alternate elements

if ($i % 3 == 0)

Apply style every 3 elements

⏰ Time conversion

$minutos = $segundos % 60

Extract minutes from total seconds

🎯 Cyclic groups

$grupo = $numero % 5

Assign to groups of 5 elements

🎯 Loop Processing Patterns

Filtering and Classification

$pares = [];
$impares = [];
foreach ($numeros as $num) {
    if ($num % 2 == 0) {
        $pares[] = $num;
    } else {
        $impares[] = $num;
    }
}

Separate elements into different categories based on conditions.

Accumulation Conditional

$suma_condicional = 0;
for ($i = 0; $i <= 100; $i++) {
    if ($i % 3 == 0) {
        $suma_condicional += $i;
    }
}

Add up only the elements that meet a certain condition.

Counting and Statistics

$contador = 0;
foreach ($datos as $dato) {
    if ($dato > $umbral) {
        $contador++;
    }
}

Count elements that meet specific criteria.

⚡ Optimization and Best Practices

✅ Initialize variables

Always initialize accumulator variables before the loop.

✅ Correct

$suma = 0;
for(...) { $suma += ... }

❌ Incorrect

for(...) { $suma += ... }

✅ Use compound operators

Operators like += are more efficient and readable.

✅ Better

$suma += $valor;

❌ Worse

$suma = $suma + $valor;

✅ Choose the right loop

Use for for ranges, foreach for arrays.

✅ Appropriate

for ($i=0; $i<10; $i++)

❌ Inappropriate

foreach (range(0,9) as $i)

🎯 Key Concepts Learned

Modulo Operator

  • Returns the remainder of a division
  • Perfect for checking divisibility
  • Used for parity, grouping, cycles
  • $a % $b = remainder of a ÷ b

Conditional Processing

  • Run different actions based on conditions
  • Combine loops with if-else
  • Classify and filter data
  • Selectively accumulate values

Accumulator Variables

  • Store cumulative results
  • Must be initialized before the loop
  • Can be sums, counters, etc.
  • Use compound operators

💪 Practical Exercise

Extend the analysis system

Practice these changes to improve your skills:

  1. Modify the code to also calculate the sum of even numbers
  2. Implement a counter for numbers divisible by 3 and 5 at the same time
  3. Create a system that finds prime numbers in the range
  4. Add separate average calculations for even and odd numbers
  5. Implement a function that receives the limit and returns complete statistics

Solution 1: Sum of evens

<?php
$suma_pares = 0;
$suma_impares = 0;

for ($i = 0; $i <= $limite; $i++) {
    if ($i % 2 == 0) {
        $suma_pares += $i;
    } else {
        $suma_impares += $i;
    }
}

echo "Suma pares: $suma_pares, Suma impares: $suma_impares";
?>

Solution 2: Divisible by 3 and 5

<?php
$divisibles = 0;
for ($i = 0; $i <= $limite; $i++) {
    if ($i % 3 == 0 && $i % 5 == 0) {
        $divisibles++;
    }
}

echo "Números divisibles por 3 y 5: $divisibles";
?>

Solution 3: Prime numbers

<?php
$primos = [];
for ($i = 2; $i <= $limite; $i++) {
    $esPrimo = true;
    for ($j = 2; $j < $i; $j++) {
        if ($i % $j == 0) {
            $esPrimo = false;
            break;
        }
    }
    if ($esPrimo) {
        $primos[] = $i;
    }
}

echo "Números primos: " . implode(', ', $primos);
?>

Solution 4: Averages

<?php
$pares = [];
$impares = [];

for ($i = 0; $i <= $limite; $i++) {
    if ($i % 2 == 0) {
        $pares[] = $i;
    } else {
        $impares[] = $i;
    }
}

$promedio_pares = count($pares) > 0 ? array_sum($pares) / count($pares) : 0;
$promedio_impares = count($impares) > 0 ? array_sum($impares) / count($impares) : 0;

echo "Promedio pares: $promedio_pares, Promedio impares: $promedio_impares";
?>

Solution 5: Function for statistics

<?php
function analizarNumeros($limite) {
    $estadisticas = [
        'pares' => [],
        'impares' => [],
        'suma_pares' => 0,
        'suma_impares' => 0
    ];
    
    for ($i = 0; $i <= $limite; $i++) {
        if ($i % 2 == 0) {
            $estadisticas['pares'][] = $i;
            $estadisticas['suma_pares'] += $i;
        } else {
            $estadisticas['impares'][] = $i;
            $estadisticas['suma_impares'] += $i;
        }
    }
    
    return $estadisticas;
}

$resultados = analizarNumeros(50);
print_r($resultados);
?>