Loading your workspace…
Loading your workspace…
Read the number of rows n and print a centred pyramid in which row i counts up from 1 to i and back down to 1.
#include <stdio.h>
int main(void) {
int rows, row, j;
printf("Enter the number of rows (1-9):\n");
if (scanf("%d", &rows) != 1 || rows < 1 || rows > 9) {
printf("Error: rows must be between 1 and 9\n");
return 1;
}
for (row = 1; row <= rows; row++) {
for (j = 1; j <= rows - row; j++) {
printf(" ");
}
for (j = 1; j <= row; j++) {
printf("%d", j);
}
for (j = row - 1; j >= 1; j--) {
printf("%d", j);
}
printf("\n");
}
return 0;
}
Input
4Output
Enter the number of rows (1-9):
1
121
12321
1234321Input
1Output
Enter the number of rows (1-9):
1Input
10Output
Enter the number of rows (1-9):
Error: rows must be between 1 and 9Each row is built from three parts: leading spaces that centre it, an ascending run of digits and a descending run that mirrors it. Row i always has i digits on the way up and i - 1 on the way down, so the row reads the same forwards and backwards.
The limit of nine rows is deliberate. Once a row reaches 10, the number 10 would print as two characters and break the pattern, so the input is restricted to one-digit values.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
4
Expected output
Enter the number of rows (1-9): 1 121 12321 1234321
1
Expected output
Enter the number of rows (1-9): 1
10
Expected output
Enter the number of rows (1-9): Error: rows must be between 1 and 9
n - i spaces, so the widest row (the last one) has none and the first row has n - 1.
The peak digit is printed once by the ascending loop, so the descent must start one below it to avoid repeating it.
The digits go up from 1 to i and back down to 1, so the row is a palindrome.
Digits above 9 take two characters and would misalign the centred pattern.
The rows are short, so printing each character directly is simpler and needs no buffer.
Back to all VTU BPOPS103 lab programs.