Cumulative Step Number Triangle in PHP

What You’ll Learn
How to print a cumulative-step number triangle in PHP using nested loops and two helper variables.
You’ll see how dynamic increments can produce non-linear row sequences.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15Complete PHP Program
Start each row at $i, then increase by a decreasing step value to generate subsequent terms.
<?php
for ($i = 1; $i <= 5; $i++) {
$k = 4;
$res = $i;
for ($j = $i; $j < $i + $i; $j++) {
if ($i == $j) {
echo $j . " ";
} else {
$res = $res + $k;
echo $res . " ";
$k--;
}
}
echo PHP_EOL;
}🧠 How It Works
Outer loop sets row
for ($i = 1; $i <= 5; $i++) controls row count and first value.
Initialize helpers
$k = 4 is step size, $res = $i stores latest printed value.
Generate row values
First value is $i. Next values use $res += $k and then $k--.
Next line
echo PHP_EOL; prints each row on a new line.
Step-based triangle rows
Rows grow from 1 to n terms, so total printed values are triangular, giving O(n²).
Variation — User Input (CLI) Version
This version accepts row count from user input (run from terminal with php):
<?php
echo "Enter number of rows: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $n; $i++) {
$k = $n - 1;
$res = $i;
for ($j = $i; $j < $i + $i; $j++) {
if ($i == $j) {
echo $j . " ";
} else {
$res += $k;
echo $res . " ";
$k--;
}
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spacing alignment with
str_pad() - Generalize step initialization for different row sizes
- Reverse sequence direction for a mirrored variant
- Store rows in arrays for reuse/testing
- Use custom starting value instead of row index
Avoid
- Using HTML wrappers in CLI-oriented pattern logic
- Forgetting to decrement step
$kafter each addition - Skipping input validation for row size
- Changing inner loop bounds without updating formula logic
Key Takeaways
Each row starts at i and adds decreasing steps.
Variables $res and $k manage sequence generation.
Inner loop prints exactly i values per row.
This demonstrates state-based pattern creation, not simple arithmetic progression.
❓ Frequently Asked Questions
$n = 8 and initialize step as $n - 1 in dynamic version.Explore More PHP Number Patterns!
Practice variable-driven sequence building with more advanced pattern programs.
Patterns like this are useful for understanding how state variables evolve across nested loops, a key concept for many dynamic programming tasks.
12 people found this page helpful
