Ajeet kumar
Ajeet kumar

Reputation: 11

How to conditionally perform math within a loop?

I want to print a series of conditionally modified numbers using a loop.

The logic is that the odd occurrences are printed without modification, but the even occurrences are squared (multiplied by themselves).

for ($i=1; $i < 6 ; $i++) { 
    echo $i;
    for ($j=1; $j==$i ; $j++) { 
        echo ($j+1) * ($j+1);
    }
    echo " ";
}

The above code prints: 14 2 3 4 5.

My desired result (if iterating 1 through 6) is:

//    unmodified
//    ↓   ↓    ↓
      1 4 3 16 5 36
//      ↑   ↑↑   ↑↑
//      squared (2, 4, and 6)

Upvotes: 0

Views: 73

Answers (3)

Barmar
Barmar

Reputation: 780889

You need to start with 1 and add 2 each time through the loop. The even elements are the squares of the number after that number. So:

for ($i = 1; $i < 6; $i += 2) {
    echo $i . " " . (($i+1) * ($i+1)) . " ";
}

You don't need the inner loop.

Upvotes: 2

Progrock
Progrock

Reputation: 7485

<?php

for($i=1; $i<=6; $i++)
    echo $i&1 ? $i : $i*$i , ' ';

Because you can determine the nth term, we could write a function to get the nth number:

function ajeet_number($n) {
    return $n&1 ? $n : $n*$n;
}

And use that in a loop:

for($i=1; $i<=6; $i++)
    echo ajeet_number($i) . ' ';

Or apply that function to a range of numbers:

$s = array_map('ajeet_number', range(1,6));
echo implode(' ', $s);

Each output of above is similar:

1 4 3 16 5 36 

Reference: Test if number is odd or even

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Another way to do it by using %

<?php
$result = [];
for ($i=1; $i < 6 ; $i++) { 
    if($i%2==0){
        $result[] = pow($i,2);
    }else{
        $result[] = $i;
    }
}
echo implode(' ', $result);
?>

Program Output

1 4 3 16 5

DEMO: https://eval.in/1027936

Upvotes: 1

Related Questions