Sequential Decreasing-Width Number Triangle in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Format

What You’ll Learn

The sequential decreasing-width number triangle prints consecutive integers in rows that get shorter each line. This tutorial covers the shape rule, the $k counter, nested loops, printf alignment, a live preview, algorithm steps, worked PHP examples, edge cases, and complexity.

Shape Rule

Shrinking row width

Row 1 prints $rows numbers, row 2 prints $rows-1, down to one number on the last line.

k Counter

Global sequence

$k = 1 tracks the next value; $k++ after each print keeps the sequence continuous.

Outer Loop

Rows

for ($i = 1; $i <= $rows; $i++) walks from the widest row to the narrowest.

Inner Loop

Decreasing count

for ($j = $rows; $j >= $i; $j--) runs fewer times as $i grows.

Live Preview

1–20 rows

Pick a row count and draw the sequential triangle instantly in the browser.

O(n²)

Complexity

Total values = n(n+1)/2; extra memory stays O(1).

Introduction

A sequential decreasing-width number triangle prints consecutive integers while each row gets one value shorter. With $rows = 5, the output is 1 2 3 4 5, then 6 7 8 9, then 10 11 12, 13 14, and 15.

In PHP you solve it with two nested for loops and a shared $k counter: the outer loop picks the row, the inner loop prints $rows - $i + 1 formatted numbers with printf("%3d", $k++), then echo PHP_EOL moves to the next line.

Why it matters?

It teaches counter-driven output and formatted columns — key skills before harder number-pattern variants.

Key Highlights

Shrinking Row Width

Row $i prints $rows - $i + 1 consecutive values.

k Counter

printf("%3d", $k++) keeps columns aligned.

Format Then Break

printf("%3d", $k++) in the inner loop; echo PHP_EOL after.

Series Foundation

Follow Program 37 palindrome rows; continue to Program 39 rotating numbers.

In short: for each row $i from 1 to $rows, print $rows - $i + 1 consecutive numbers with printf("%3d", $k++), then call echo PHP_EOL.

📝 Problem & Approach

Given a positive integer $rows, print consecutive integers starting at 1 in a triangle where row $i contains exactly $rows - $i + 1 values.

PHP
// First 5 rows (conceptual shape)
//   1  2  3  4  5
//   6  7  8  9
//  10 11 12
//  13 14
//  15

Inputs & Outputs

ItemTypeDescription
$rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextLeft-aligned rows of consecutive integers; row $i has $rows - $i + 1 values.

Minimal workflow

Pseudocode
for i from rows down to 1:
    if i is even:
        for j from i down to 1: print j
    else:
        for j from 1 to i: print j
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + k counterOuter rows + inner shrinking width + formatLearning and interviews
Custom start kChange initial k instead of 1Variations and demos

⚡ Quick Reference

GoalPattern
Walk each rowfor ($i = 1; $i <= $rows; $i++)
Print shrinking countfor ($j = $rows; $j >= $i; $j--) printf("%3d", $k++);
End the rowecho PHP_EOL;
Wider columnsprintf("%4d", $k++); for larger totals
Program 37 variantPalindrome per row instead of global sequence

📋 echo vs printf vs sprintf

Same triangle — different ways to emit aligned numbers.

echo
no padding

Digits run together — columns misalign at 10+

printf
%3d

Right-aligns each value in a 3-character field

sprintf
returns string

Builds formatted text without printing directly

Learning tip
$k counter

Master the $k++ pattern before wider field widths

Context

When This Pattern Shows Up

Reach for this pattern when teaching counters and formatted output inside nested loops.

  1. First lab exercise

    Most PHP pattern series start here before pyramids and diamonds.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible row count.

  4. Gateway to variants

    Compare Program 37 palindrome rows and Program 39 rotating numbers next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the sequential decreasing-width triangle in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed row count, fgets(STDIN) input, and a custom starting value for $k. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with nested loops, a $k counter, and formatted output.

Example 1 — Fixed $rows = 5

Hard-coded height — ideal for first demos and screenshots.

PHP
<?php
$rows = 5;
$k = 1;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $rows; $j >= $i; $j--) {
        printf("%3d", $k++);
    }
    echo PHP_EOL;
}

How It Works

When $i = 1, the inner loop runs 5 times and prints 1 through 5. When $i = 2, it prints 6 through 9, and so on until the last row prints 15. echo PHP_EOL after the inner loop starts the next row.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with fgets(STDIN).(int) trim(fgets(STDIN)) (check is_numeric() in real apps).

PHP
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) return;
$rows = (int) $input;
if ($rows < 1) return;

$k = 1;
for ($i = 1; $i <= $rows; $i++) {
    for ($j = $rows; $j >= $i; $j--) {
        printf("%3d", $k++);
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop core as Example 1; only the source of $rows changes. Non-numeric input throws invalid input with (int) trim(fgets(STDIN)) — check is_numeric() for safer labs.

⚡ Variation

Same shape with a different starting value for the sequence.

Example 3 — Custom Start $k = 10

Initialize $k with any starting value — the inner loop logic stays the same.

PHP
<?php
$rows = 5;
$k = 10;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $rows; $j >= $i; $j--) {
        printf("%3d", $k++);
    }
    echo PHP_EOL;
}

How It Works

Only the initial value of $k changes. The shrinking inner loop still prints $rows - $i + 1 values per row. Great for variations once you understand the default $k = 1 version.

🧠 How the Algorithm Prints Rows

1

Set up

Set $rows = 5; and use fgets(STDIN) when reading input. Set loop variables $i, $j, $k.

Setup
2

Outer loop (rows)

for ($i = 1; $i <= $rows; $i++) selects the current row from widest to narrowest.

Row
3

Inner loop (values)

for ($j = $rows; $j >= $i; $j--) prints $rows - $i + 1 numbers with printf("%3d", $k++).

Print
4

New line

echo PHP_EOL ends the row so the next outer iteration starts fresh.

Break
=

Triangle complete

Total digit prints: 1+2+…+n = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — $rows = 4

Trace each outer-loop value of $i, the inner-loop count, and the values printed via $k.

$iInner runs$k rangePrinted row
141..41 2 3 4
235..75 6 7
328..98 9
411010

Total value prints: 1 + 2 + 3 + 4 = 10 = 4×5/2.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change $j <= $i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: change $k start to 100 for a shifted sequence.

3. Console Formatting Drills

Practice echo vs echo PHP_EOL without complex math.

Example: put echo PHP_EOL inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: use %4d when values exceed two digits.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with fgets(STDIN) and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner PHP courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the $k-counter nested-loop version first; then try custom start values or wider format widths.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use $rows (or n) and keep $i/$j for row/column — or rename to row/col.

  2. 2. Prefer trim(fgets(STDIN))

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep echo PHP_EOL Outside

    Only call echo PHP_EOL after the inner loop finishes the row.

  4. 4. Pick Field Width Early

    Use %4d or wider when total values exceed 99.

  5. 5. Dry-Run One Small n

    Trace $rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put echo PHP_EOL inside the inner loop.

Common Pitfalls

Mistakes that commonly break sequential decreasing-width number patterns.

  1. 1. echo PHP_EOL Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use printf("%3d", $k++) for values; echo PHP_EOL only after the inner loop.

  2. 2. Wrong Inner Bound

    Using $j <= $rows on every row prints a rectangle; resetting $k each row breaks the sequence.

    → Keep for ($j = $rows; $j >= $i; $j--) and one shared $k.

  3. 3. Forgetting the Row Break

    Omitting echo PHP_EOL glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked CLI input

    Letters or empty input throw undefined rows.

    → Prefer trim(fgets(STDIN)) and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to $i = 0 without adjusting the inner bound prints an empty first row or wrong counts.

    → If 0-based, print $i with wrong inner bound (e.g. $j <= $i + 1).

Edge Cases

Check these inputs before calling the solution done.

$rows = 1

Single digit

Output is just 1 on one line.

$rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric CLI input

Unchecked fgets(STDIN) leaves $rows unset — call is_numeric($input) first.

Fill char

Custom start k

Initialize $k to any value — the sequence continues from there.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Palindrome number triangle

  • Build symmetric rows like 4321234
  • Continue with Program 37

2. Rotating number pattern

  • Shift the sequence each row (23451, 34521, …)
  • Continue with Program 39

3. Upside-down triangle

  • Start with one number and grow row width each line
  • Reverse outer and inner loop bounds

4. Wider format

  • Use %4d or %5d for larger triangles
  • Keeps columns aligned past two digits

Notes

  • Triangular count. Total digit prints for n rows is n(n+1)/2 — hence O(n²) time.
  • print stays on the line; println advances — mix them carefully.
  • Validate $rows > 0 for interactive programs; $rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop picks the row, inner loop prints shrinking count with $k++, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Custom start k (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The sequential decreasing-width number triangle combines nested loops with a shared $k counter and formatted output — a natural step after palindrome rows. Master the default $k = 1 version, then optionally change the start value or field width.

Practice the three examples above, then continue to Program 39 for the rotating number pattern.

Row $i prints $rows - $i + 1 consecutive values — keep printf("%3d", $k++) for digits and echo PHP_EOL for the break.

💡 Best Practices

✅ Do

  • Explain $k counter and shrinking inner bound before coding
  • Use printf("%3d", $k++) for values and echo PHP_EOL after each row
  • Validate rows ≥ 1 for interactive programs
  • Check is_numeric($input) return value before using $rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call echo PHP_EOL inside the inner digit loop
  • Reset k inside the outer loop (breaks the global sequence)
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the $rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this sequential pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Controls each row

Code
k 03

$k counter

$k++ after each print

Logic
# 04

printf %3d

Aligns columns

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Because the row lengths are 5, 4, 3, 2, and 1. Their sum is 5+4+3+2+1 = 15, which equals n(n+1)/2.
%3d prints an integer right-aligned in a field width of 3 characters, which keeps columns aligned when numbers reach two digits.
Each row prints a different count of numbers, but the sequence must continue globally (1, 2, 3, ...). $k stores the next value and increments after every print.
Yes. Initialize $k with your starting value instead of 1, for example $k = 10.
Program 37 builds a palindrome on each row (4321234). Program 38 prints one continuous ascending sequence with shrinking row widths.
O(n²) where n is the number of rows. Total printed values equal 1+2+…+n = n(n+1)/2.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Row $i prints $rows - $i + 1 consecutive numbers via a shared $k counter. Total values for n rows is the triangular number n(n+1)/215 when $rows = 5.

Continue to Program 39

Move on to the rotating number pattern in the PHP number-pattern series.

Program 39 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful