Home >Backend Development >PHP Tutorial >PHP custom display first few lines of Floyd triangle
This article will introduce you to a more interesting PHP implementation. First of all, do you know what a Floyd triangle is?
It doesn’t matter if you don’t know this term. Let’s look at the picture below and it will be clear at a glance:
Floyd’s triangle is also called Floyd’s triangle. A series of numbers, as shown in the picture above, these numbers are distributed sequentially on a series of rows; the first row contains a 1, the second row contains 2 and 3; the next row contains 4, 5 and 6... These numbers start with This pattern continues indefinitely to produce a right triangle, with the numbers spaced at even intervals.
Let's write a PHP program to generate and display the first n rows of Freud's triangle, that is, the first few rows.
Without further ado, the code is as follows:
<?php $n = 6; echo "n = " . $n . "<br>"; $count = 1; for ($i = $n; $i > 0; $i--) { for ($j = $i; $j < $n + 1; $j++) { printf("%4s", $count); $count++; } echo "<br>"; }
The generated result is:
You can directly copy the above code in Local testing.
In fact, coding Freud’s triangle correctly requires proficiency in loop knowledge. The for loop in PHP is mainly used here. The for loop is used when you know in advance the number of times the script needs to be run. Its syntax is:
for (初始值; 条件; 增量){ 要执行的代码;}
The parameters respectively represent:
初始值:主要是初始化一个变量值,用于设置一个计数器(但可以是任何在循环的开始被执行一次的代码)。 条件:循环执行的限制条件。如果为 TRUE,则循环继续。如果为 FALSE,则循环结束。 增量:主要用于递增计数器(但可以是任何在循环的结束被执行的代码)。
For a detailed introduction to the for loop, you can read the chapter "PHP For Loop" in the PHP manual.
Finally, I would like to recommend to you the latest free course on our platform "Entering the World of PHP from 0"~ Come and learn!
The above is the detailed content of PHP custom display first few lines of Floyd triangle. For more information, please follow other related articles on the PHP Chinese website!