Home >Backend Development >PHP Tutorial >Two methods of printing Yang Hui triangle with PHP

Two methods of printing Yang Hui triangle with PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:13:001421browse

Example 1, print Yang Hui triangle directly in a loop.

  1. //Yang Hui Triangle
  2. for ($i=6;$i >= 0;$i--)
  3. {
  4. for ($j=$i;$j < = 6;$j++)
  5. {
  6. if ($j <= 6-1)
  7. {
  8. echo "a";
  9. }else
  10. {
  11. echo "
    ";
  12. }
  13. }
  14. }
  15. ?>
Copy code

Example 2, PHP prints Yang Hui's triangle custom function

  1. Input the order of Yang Hui's triangle:
  2. //Yang Hui Triangle Custom function
  3. function yanghui($line)
  4. {
  5. echo "";
  6. for($i=1;$i<=$line;$i++)
  7. {
  8. echo "
  9. ";
  10. for($j=1;$j<=$i;$j++)
  11. {
  12. $yh[$i][1]=1;
  13. if ($i==$j) $yh[$i][ $j]=1;
  14. else $yh[$i][$j]=$yh[$i-1][$j-1]+$yh[$i-1][$j];
  15. echo "
  16. ";
  17. }
  18. echo "
  19. ";
  20. }
  21. echo "
  22. ";
  23. echo $yh[$i][$j];
  24. echo "
  25. ";
  26. }
  27. if($_POST['submit']) yanghui($_POST['givenlines']);
  28. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn