Print a pyramid of numbers.
What to build
A pattern made with loops inside a loop.
Requirements
- Read
n. - Row
r, counting from 1, hasn - rspaces, then the digits from 1 up tor, then back down to 1. - Do not print spaces after the last digit.
Input
One whole number n.
Output
n lines.
Constraints
n is from 1 to 9.
Example
Input:
3
Output:
1
121
12321
Why it works
Each row can be worked out from its row number alone, so a single outer loop with three small inner loops builds the whole shape.
Examples
Example 1 · Input
3
Expected output
1 121 12321
Example 2 · Input
1
Expected output
1
Hints
Hint 1
Row r needs n - r spaces first.
Hint 2
Then count up to r, and back down to 1.
Hint 3
Use separate loops for the spaces, the rising numbers and the falling numbers.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int r = 1; r <= n; r++) {
for (int s = 0; s < n - r; s++) {
cout << " ";
}
for (int d = 1; d <= r; d++) {
cout << d;
}
for (int d = r - 1; d >= 1; d--) {
cout << d;
}
cout << endl;
}
return 0;
}