PHP custom display first few lines of Floyd triangle

藏色散人
Release: 2023-04-10 13:52:02
Original
1942 people have browsed it

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:

PHP custom display first few lines of Floyd triangle

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:

"; $count = 1; for ($i = $n; $i > 0; $i--) { for ($j = $i; $j < $n + 1; $j++) { printf("%4s", $count); $count++; } echo "
"; }
Copy after login

The generated result is:

PHP custom display first few lines of Floyd triangle

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 (初始值; 条件; 增量){ 要执行的代码;}
Copy after login

The parameters respectively represent:

初始值:主要是初始化一个变量值,用于设置一个计数器(但可以是任何在循环的开始被执行一次的代码)。 条件:循环执行的限制条件。如果为 TRUE,则循环继续。如果为 FALSE,则循环结束。 增量:主要用于递增计数器(但可以是任何在循环的结束被执行的代码)。
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!