unable to get the correct output pattern in php

Viewed 93

i am trying to get this pattern in php:

enter image description here

i have tried but i i'm unable to produce the output, as my output is coming like :

run-project -l php
5
        0
      01
    012
  0123
01234

However, the code is:

<?php
function print_pattern($num)
{
  for ($i = 0; $i < $num; $i++)
  {
    for($k = $num; $k > $i+1; $k-- )
      {
      echo "  ";
      }
    for($j = 0; $j <= $i; $j++ )
      {
      echo $j;
      }
  echo "\n";
  }
}
$num = (int)readline();
print_pattern($num);
?>
3 Answers

Your expectation is to have numbers printed on each line in an incremental order

12 First line 2 Numbers

345 Second Line 3 numbers (Continued from First line)

6789 Third Line 4 numbers (Continued from Second line)

and goes on.....

 <?php 

function print_pattern($num)
{
  $breaker = 2; // since you want the first line to have 2 Numbers
  $ticker = 1; // This is to track numbers for each line
  for ($i = 1; $i <= $num; $i++)
  {
    if ($ticker <= $breaker) { 
          echo $i;
    } else  {
        echo '<br>';
        $ticker = 1; // Reset ticker
        echo $i;
        $breaker++; // increment breaker
    }
     $ticker++; // increment ticker
  }
}
 
print_pattern(20);


 ?>

Simple Approach: Use just two loops one for rows which her index is $i and the second for columns $j, first loop loops through number of rows. and second loop will accumulate the result of $k which will be incremented on each loop.

function print_pattern($num)
{
  $k = 1;
  for ($i = 1; $i <= $num; $i++)
  {
    $line = '';
    for ($j = 0; $j <= $i; $j++)
    {
        $line .= $k;
        $k++;
    }
    echo str_pad($line, 12, " ", STR_PAD_LEFT);
    echo "</br>";
  }
}

Result

echo "<pre>";
print_pattern(5);
/*
          12
         345
        6789
  1011121314
151617181920
*/

Hint: Use str_pad function to show the output starts from the right side.

This is another method

function print_pattern($num)
{
  $j = 1;
  for ($i = 1; $i <= $num; $i++)
  {
    $count = 1;
    while($count <= $i+1) 
    {
        echo $j;
        $j++;
        $count++;
    }
    echo "<br>";
  }
}
$num = 5;
print_pattern($num);

another method

Related