Reputation: 340
Recently I had an interview in which I was asked to make a output of the following kind:
9
1
8
2
7
3
6
4
Now I hadn't practiced much but somehow managed to make this .
In which i use 2 variables $i($i=1)
and $num($num=9)
.
And make the condition $i<5
and increase it by one till it reaches 5.
<?php
$num=9;
for($i=1;$i<5;$i++) {
echo $num . "<br>". $i."<br>";
$num--;
}
?>
Which gives the output I require. But there another way of doing it by using $i
and $j
as the variables. So I want to know which one is simpler and better.
<?php
for($i=1,$j=9; $j>=6; $i++,$j--){
echo($j."<br/>".$i."<br />");
}
?>
Upvotes: 1
Views: 135
Reputation: 1291
One variable solution
for($i=1; $i<5; $i++) {
echo 10 - $i . "<br>". $i."<br>";
}
Upvotes: 1
Reputation: 55457
More generically this can be written as:
<?php
//Bounds
$upper = 9;
$lower = 1;
//Mid-point, use MOD 2 to add 1 for odd numbers
$mid = ( $upper + ( $upper % 2 ) ) / 2;
for( $i = $lower, $j = $upper; $i <= $mid && $j > $mid; $i++, $j-- )
{
echo $j;
echo "\n";
echo $i;
echo "\n";
}
It gets a little vague towards the end of the sequence. The sequence that you provided completely ignores the center/pivot number (5) and the above code does the same for an odd range of numbers but shows them for even ranges. If the goal is to always ignore the center one or two (odd or even) then you can change the second center condition in the for
loop:
for( $i = $lower, $j = $upper; $i < $mid && $i !== $j; $i++, $j-- )
{
echo $j;
echo "\n";
echo $i;
echo "\n";
}
Upvotes: 1
Reputation: 11
I think it would be preferable to run a loop that decrements from 9 and use a variable to track the number of iterations:
$count = 0;
for ($i = 9; $i >= 6; $i--)
{
$count++;
echo $i."\n";
echo $count."\n";
}
Upvotes: 1
Reputation: 1545
This looks better for me
for ($i=1, $j=9; $i<5; $i++,$j--) {
echo $j;
echo "\n";
echo $i;
echo "\n";
}
Upvotes: 1