Robson » Little Red Book » Number pyramid

Chapter 6 - Question 6

Design a program to produce a number pyramid. That is, given a starting digit from 1 to 9 produce a pyramid containing that number of lines, beginning with a 1 and continuing, on each successive line, with an ascending - descending sequence from 1 to the number and back again.

Solution 1

<?
   // generate a random number of lines to create
   $lines = mt_rand(1, 9);
 
   // store numbers for use later
   $numbers = '123456789';
   
   // show fixed width
   echo '<pre>' . $lines . ':<br/>';
   
   // loop through each line
   for ($n = 1; $n <= $lines; $n++)
   {
       // create spaces to form the pyramid effect
       $spaces = str_repeat(' ', $lines-$n);
       // show the numbers ascending and then descending
       $line = substr($numbers, 0, $n) . strrev(substr($numbers, 0, $n-1));
       // output this line of the pyramid
       echo $spaces . $line . '<br/>';    
   }
   
   // return to normal widths
   echo '</pre>';
?>

Which produces:

7:
1
121
12321
1234321
123454321
12345654321
1234567654321

Log

© 2004-17 robson | cc unless stated