php
  1. php-number-triangle

PHP Number Triangle

Syntax

Here is the basic syntax for creating a number triangle in PHP:

$num = 5;
for ($i = 1; $i <= $num; $i++) {
  for ($j = 1; $j <= $i; $j++) {
    echo $j . " ";
  }
  echo "<br>";
}

Example

Let's use the above syntax to create a number triangle with a base of 5:

$num = 5;
for ($i = 1; $i <= $num; $i++) {
  for ($j = 1; $j <= $i; $j++) {
    echo $j . " ";
  }
  echo "<br>";
}

Output

The above code will output the following number triangle:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Explanation

The inner for loop is used to print the numbers on each line. The outer for loop is used to repeat the inner loop and create multiple lines.

Use

Number triangles can be useful in developing games, data structures, and other mathematical applications.

Important Points

  • A nested loop is used to create a number triangle.
  • The first loop controls the number of lines (height).
  • The second loop controls the numbers on each line (width).

Summary

Number triangles are a common programming challenge and can be useful in various applications. PHP provides a simple and easy method to create number triangles using nested loops. By understanding the basic syntax and concepts, you can create more complex and interesting number triangles.

Published on: