Nested thinking: each row of a pyramid is made of spaces, a rising run and a falling run of digits.
What to build
A program that prints a number pyramid with n rows.
Requirements
- Read n.
- Row i (from 1 to n) starts with n - i spaces, then the digits 1 up to i, then i - 1 down to 1, as in the example.
Input
One integer n.
Output
n lines.
Constraints
1 ≤ n ≤ 9.
Example
Input:
3
Output:
1
121
12321
Why it works
The spaces move the row to the right place, and the two inner loops write the rising and the falling digits.
Examples
Example 1 · Input
3
Expected output
1 121 12321
Example 2 · Input
1
Expected output
1
Hints
Hint 1
For row i print n - i spaces first.
Hint 2
Then count up from 1 to i and back down from i - 1 to 1, using two small loops.
Solution
Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
for ($i = 1; $i <= $n; $i++) {
echo str_repeat(" ", $n - $i);
for ($j = 1; $j <= $i; $j++) {
echo $j;
}
for ($j = $i - 1; $j >= 1; $j--) {
echo $j;
}
echo "\n";
}