1

I'm supposed to use nested for loops to create this shape: https://i.stack.imgur.com/le3lX.jpg

This is what I currently have:

 <?php
 for ($x = 1; $x <= 10; $x++){

      for ($y = 1; $y <= 6; $y++){
                    echo "Y";
      }
 }
?>

I have no clue what to do. Thanks in advance!

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Atlaz
  • 13
  • 3

4 Answers4

1
<?php
$position = 1;
for ($x = 1; $x <= 11; $x++){
    for ($y = 1; $y <= 6; $y++){
        if ($y == $position) {
            echo "Y";
        } else {
            echo "0";
        }
    }
    if ($x < 6) {
        $position++;
    } else {
        $position--;
    }
    echo "\n";
}
Dmytro
  • 321
  • 1
  • 10
0
 <?php
 $length = 6; // change this to change height width
 $pos = 0;
 for ($x = 1; $x <= (($length*2)-1); $x++){
    if($x <= $length)
    {$pos = $pos+1; }
    else
    {$pos = $pos-1; }
      for ($y = 1; $y <= $length; $y++){
                    if($y == $pos)
                    echo "Y";
                    else
                    echo "O";
      }
      echo "\n";
 }
Manpreet
  • 2,450
  • 16
  • 21
0
$k=2;                   // for calculating position from backside
for($i=1;$i<=11;$i++)    //for row
  {
   for($j=1;$j<=6;$j++)       //column
    {
       if($j==$i && $i<=6)      //logic for printing "Y" till the end of row
           echo "Y";
       else if($i>6 && $j==($i-$k))    //logic for printing "Y" in reversal order from the end of row
       {
          echo "Y";
          $k+=2;                       
       }
        else
          echo "O";                   // filling rest places with "O"
    }
   echo"\n";                             // jumping to new Row;
 }

Hope you can understand it easily.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
S.M
  • 601
  • 7
  • 17
0

There are many possible ways to achieve this when I started programming I never cared about the code quality and just focused on the output. I have added two examples to help you understand it better!

<?php

//We have 6 columns & 11 rows so we need two loops one size of 11 and second size of 6
$counter = 1;
for ($i = 1; $i <= 11; $i++){
    for ($j = 1; $j <= 6; $j++){
        if ($j == $counter) {
            echo "Y";
        } else {
            echo "O";
        }
    }
    if ($i < 6) {
        $counter++;
    } else {
        $counter--;
    }
    echo "<br/>";
}

echo "**************************** METHOD TWO ****************************";
//Following is not efficient But its also printing the same results
for ($i = 0 ; $i < 66 ; $i++){

    if($i == 65)
    {
        echo "O";
        break;
    }
    if($i % 6 == 0){
        echo "<br/>";
    }
    if($i <= 36)
    {
        if ($i % 7 == 0){
            echo "Y";
        }else{
            echo "O";
        }
    }else{
        if ($i % 5 == 0){
            echo "Y";
        }else{
            echo "O";
        }
    }
}
?>
Ussaid Iqbal
  • 786
  • 1
  • 7
  • 16