PHP Number Triangle Pattern (Odd/Even Rows)

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

What Is This Pattern?

An alternating odd/even number triangle grows by one number each row, but switches between odd-only and even-only sequences based on the row’s parity.

Remember
Rule: odd rows start at 1; even rows start at 2;
      then print i numbers with k += 2

1
2 4
1 3 5
2 4 6 8
1 3 5 7 9   ← rows = 5

In PHP you pick start value $k with $i % 2, print $k with a trailing space, update $k += 2, then echo PHP_EOL ends the row. Program 17 was odd-only with a left shift; this pattern flips parity per row.

How to Solve It

Pick the start with row parity, then print a growing odd or even stream with $k += 2.

MethodIdeaBest for
if / else startOdd → $k = 1; even → $k = 2Learning, interviews, exams
Ternary start$k = ($i % 2 === 0) ? 2 : 1Shorter demos once parity clicks

Pseudocode

Pseudocode
for i from 1 to rows:
    if i is even:
        k = 2
    else:
        k = 1
    for j from 1 to i:
        print k and a space
        k = k + 2
    print newline

Cheat sheet

GoalPattern
Grow row lengthfor ($i = 1; $i <= $rows; $i++)
Pick start$k = ($i % 2 === 0) ? 2 : 1;
Print + stepecho $k . " "; $k += 2;
End the rowecho PHP_EOL;
Flip parity$k = ($i % 2 === 0) ? 1 : 2;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $k . " "Stays on the same lineEach number in the row
echo PHP_EOLEnds the current lineAfter the inner loop

Print all numbers without a newline, then end the row once.

Live Preview

Change the height and the odd/even triangle updates instantly.

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

Live result 5 rows · 15 numbers
1
2 4
1 3 5
2 4 6 8
1 3 5 7 9

Worked Walkthrough

Trace four outer values when $rows = 5 — watch parity pick the start and $k += 2 keep the sequence.

$iParityStart $kPrinted row
1odd11
2even22 4
3odd11 3 5
4even22 4 6 8

Total numbers are 1+2+3+4+5 = 15 — the triangular number n(n+1)/2.

PHP Programs

Three complete programs: fixed height, CLI input with a ternary start, and flipped parity. Use View Output for sample results.

Example 1 — Fixed $rows = 5

Hard-coded height — if/else picks the start; the inner loop prints and steps by 2.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    if ($i % 2 === 0) {
        $k = 2;
    } else {
        $k = 1;
    }

    for ($j = 1; $j <= $i; $j++) {
        echo $k . " ";
        $k += 2;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Outer loop grows width. Row $i prints exactly $i numbers.

2. Parity picks the start. Even $i → $k = 2; odd $i → $k = 1.

3. Inner loop prints and steps. Print $k, then $k += 2 so the row stays odd-only or even-only.

Example 2 — User Input

Read the row count from the CLI. Prefer is_numeric in real apps (shown in the tip below).

PHP
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));

for ($i = 1; $i <= $rows; $i++) {
    $k = ($i % 2 === 0) ? 2 : 1;

    for ($j = 1; $j <= $i; $j++) {
        echo $k . " ";
        $k += 2;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Prompt and read. Ask for a row count, then trim(fgets(STDIN)) and cast to int.

2. Same core, shorter start. The ternary ($i % 2 === 0) ? 2 : 1 replaces the if/else block.

3. Safer input tip. Bare (int) casts turn letters into 0. Prefer:

Safer input
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 1) {
    echo "Enter a positive whole number." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

Example 3 — Flipped Row Parity

Even rows print odds; odd rows print evens — only the start assignment changes.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    $k = ($i % 2 === 0) ? 1 : 2;

    for ($j = 1; $j <= $i; $j++) {
        echo $k . " ";
        $k += 2;
    }
    echo PHP_EOL;
}
?>

How It Works

1. Swap the start map. Even $i → $k = 1; odd $i → $k = 2.

2. Same print + step. Inner loop and $k += 2 are unchanged.

3. Same triangle shape. Only which sequence lands on odd vs even rows flips.

Edge Cases & Pitfalls

Check these before calling the solution done.

wrong step

Use $k += 2, not $k++

If you use $k++, rows mix odds and evens. Keep the step at 2.

fixed start

All odds or all evens

Forgetting the parity check makes every row start at 1 (or 2). Use $i % 2 to switch.

PHP_EOL inside

echo PHP_EOL inside the inner loop

That puts each number on its own line. Print numbers without a newline; call echo PHP_EOL only after the row finishes.

rows = 1

Single number

Output is just 1 — a good sanity check for the odd-start path.

rows ≤ 0

Empty output

The outer loop never runs. Validate and prompt again for clearer UX.

spaces

Keep the trailing space

The classic sample uses echo $k . " " so numbers stay spaced and readable.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input / flipped (Examples 1–3)O(n²)O(1)

There are n rows printing 1+2+…+n numbers, so total work is n(n+1)/2.

Key Takeaways

  • Rule: odd rows start at 1; even rows start at 2; then step by 2.
  • Width: row $i prints exactly $i numbers.
  • echo vs PHP_EOL: numbers stay on the line; echo PHP_EOL advances after each row.
  • Next step: Program 19 fills a triangle with the constant digit 5.

One line: set $k from row parity, print $i numbers with $k += 2, then echo PHP_EOL.

Frequently Asked Questions

We check $i % 2. If $i is odd, set $k = 1 for odd numbers; if $i is even, set $k = 2 for even numbers.
Row 2 is even, so $k starts at 2. The inner loop prints $k then adds 2 twice: 2, then 4.
echo $k . " " stays on the same line with a trailing space. echo PHP_EOL ends the current line. Numbers use echo; the row break uses echo PHP_EOL after the inner loop.
Row 3 is odd, so $k starts at 1 and increments by 2 three times: 1, 3, 5.
After printing $k, update $k += 2 so the sequence stays odd or even while increasing.
Yes. Swap the condition so even rows start at 1 and odd rows start at 2 — see Example 3.
O(n²) for n rows. Total number prints equal 1+2+…+n = n(n+1)/2.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int so bad input does not produce unexpected results.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you know?

Row parity picks the start value: odd rows begin at 1, even rows at 2. Then $k += 2 keeps each row odd-only or even-only — still O(n²) total prints for n rows.

Next: Fill with 5 Triangle

Continue with a triangle filled by the constant digit 5.

Program 19 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