PHP Incremental Number Triangle Pattern (Right-Aligned)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A right-aligned continuous counter triangle prints a growing sequence with counter $k that never resets — leading pads while $j > $i, then printf("%3d", $k++).

Remember
Rule: k = 1
      for i from 1 to rows
        for j from rows down to 1
          if j > i: print 3 spaces
          else: print k (width 3); k++

              1
           2  3
        4  5  6
     7  8  9 10
 11 12 13 14 15     ← rows = 5

Follows the zero-based triangle in Program 34; next is the right-aligned decreasing triangle in Program 36.

How to Solve It

Outer loop grows $i. One fixed-width inner loop runs $rows..1 — print a 3-space pad or the next $k with printf("%3d", …).

MethodIdeaBest for
Fixed width + $k++Spaces while $j > $i; else print and increment $kLearning, interviews, exams
%3d columnsKeeps two-digit values aligned with single digitsReadable demos past 9

Pseudocode

Pseudocode
k = 1
for i from 1 to rows:
    for j from rows down to 1:
        if j > i: print 3 spaces
        else: print k in width 3; k = k + 1
    print newline

Cheat sheet

GoalPattern
Grow each rowfor ($i = 1; $i <= $rows; $i++)
Fixed widthfor ($j = $rows; $j >= 1; $j--)
Leading padsif ($j > $i) echo " ";
Next numberprintf("%3d", $k++);
End of rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo " " / printf("%3d", $k++)Stays on the same lineEach pad or number on the row
echo PHP_EOLEnds the current lineAfter the fixed-width loop finishes

Print characters without a newline, then end the row once.

Live Preview

Change the row count and the right-aligned counter updates instantly — capped at 7 for readable demos.

Whole numbers from 1 to 7. Tap a chip or type a value — the preview redraws as you go.

Live result rows = 5 · 15 numbers
              1
           2  3
        4  5  6
     7  8  9 10
 11 12 13 14 15

Worked Walkthrough — $rows = 5

Trace how leading pads shrink and counter $k keeps climbing.

$iPadsNumbersPrints
1411
232 32 3
324 5 64 5 6
417..107 8 9 10
5011..1511 12 13 14 15

Pads = rows − i. Numbers printed = n(n+1)/2 → O(n²).

PHP Programs

Three complete programs: fixed $rows = 5, CLI input, and a compact $rows = 3 demo. Use View Output to reveal sample results.

Example 1 — Fixed $rows = 5

Hard-coded height — continuous $k with printf("%3d", …) and leading pads.

PHP
<?php
$k = 1;

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

How It Works

1. Counter lives outside. $k starts at 1 and only advances when a number prints.

2. Fixed width. Inner loop always runs 5 times — unused left slots become " ".

3. Width 3 columns. printf("%3d", …) keeps 10 and 11 aligned with single digits.

Example 2 — User Input Rows

Read $rows from the CLI, validate, then use the same counter and pad logic.

PHP
<?php
echo "Enter rows: ";
$input = trim(fgets(STDIN));

if (!is_numeric($input) || (int) $input <= 0) {
    echo "Please enter a positive integer." . PHP_EOL;
    exit(1);
}

$rows = (int) $input;
$k = 1;

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

How It Works

1. Prompt and validate. Reject non-numeric and non-positive values before printing.

2. Same core. Pads + printf("%3d", $k++) match Example 1 — only $rows comes from the user.

3. Safer input tip. Cap demos for readable output:

Safer input
if (!is_numeric($input) || (int) $input < 1 || (int) $input > 7) {
    echo "Enter a whole number from 1 to 7." . PHP_EOL;
    exit(1);
}

Example 3 — Compact $rows = 3

Same structure with only three rows — easy to confirm pads shrink and $k never resets.

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

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

How It Works

1. Three rows. Ends at 6 — if $k reset each row you would see 1, 1 2, 1 2 3.

2. Trace on paper. If the inner loop stops at $i instead of $rows, right alignment is lost.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for five rows or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

k = 1

Resetting the counter

Putting $k = 1 inside the outer loop restarts every row. Declare $k once before both loops.

no %3d

Broken columns

Without printf("%3d", …), two-digit values misalign with single digits. Keep fixed width.

width ≠ 3

Pad mismatch

Leading pads must match number width — use " " (3 spaces) with %3d.

PHP_EOL inside

Broken rows

If echo PHP_EOL sits inside the inner loop, you get one cell per line. Call it only after the loop.

rows = 1

Single value

Output is just 1 with no leading pads. A good sanity check for input validation.

fgets

Check is_numeric

Bare (int) casts turn non-numeric strings into 0 — prefer is_numeric before casting.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Compact rows = 3 (Example 3)O(n²)O(1)

Each of n rows visits n columns (pads or numbers). Numbers printed = n(n+1)/2 → O(n²) time. Only a few loop variables are needed.

Key Takeaways

  • Continuous $k: declare once outside; use $k++ only when printing a number.
  • Fixed width: $j = $rows..1 with pads when $j > $i keeps the triangle right-aligned.
  • %3d: match pad width to number width so two-digit values stay aligned.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each row $i, walk $j = $rows..1 and print a pad or printf("%3d", $k++), then echo PHP_EOL.

Frequently Asked Questions

A right-aligned continuous counter triangle: for rows=5 you get indented 1 / 2 3 / 4 5 6 / 7 8 9 10 / 11 12 13 14 15 — $k never resets between rows.
Numbers keep increasing across rows without resetting — row 1 prints 1, row 2 prints 2 3, row 3 prints 4 5 6, and so on.
Before printing numbers on each row, the program prints three spaces while $j > $i. This indents the left side so numbers shift right.
The format specifier reserves 3 columns per number (right-aligned), keeping columns aligned when values become two digits.
$k is declared outside the loops and increments with $k++ each time a number prints, so the sequence continues across rows.
Program 30 prints descending digits per row. Program 35 uses a continuous counter $k with fixed-width formatting.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.
O(n²) for n rows because total prints are 1 + 2 + … + n = n(n+1)/2.

Did you know?

A counter $k starts at 1 and increments every time a number is printed. Leading spaces appear while $j > $i, and printf("%3d", $k++) keeps columns aligned as values grow past single digits.

Next: Right-Aligned Decreasing Triangle

Continue with a right-aligned pattern that counts downward.

Program 36 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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