Triangular Numbers

Triangular numbers count the number of objects in an equilateral triangle. 1, 3, 6, 10... When would you use this? Probably never.

Language: PHP

  1. <?php
  2.  
  3. // If x is the number of bullets for each side of the triangle
  4. // and y is the total number of bullets in the entire triangle
  5. // and x = 4
  6. $x = 4;
  7.  
  8. echo "x = " .$x. "<br />\r\n";
  9.  
  10. // Then...
  11. echo "(x^2 + x) / 2 = y<br />\r\n";
  12.  
  13. // then y = ?
  14.  
  15.  
  16. // The above but converted for PHP
  17. $y = (pow($x, 2) + $x) / 2;
  18.  
  19. // So now...
  20. echo "<b>y = " .$y. "</b><br>\r\n";
  21.  
  22. while($x > 0) {
  23. $i = 1;
  24. while($i <= $x) {
  25. echo '&bullet;&nbsp;&nbsp;&nbsp;'."\r\n";
  26. $i++;
  27. }
  28. echo '<br>';
  29. $x--;
  30. }
  31.  
  32. ?>

See It In Action