Print an Inverted Half Pyramid Number Pattern in C
To print an inverted half-pyramid number pattern in C, we use nested loops where the outer loop controls the rows, and the inner loop prints numbers in descending order, reducing the count in each iteration.
Examples of Inverted Half Pyramid Number Pattern
1. Basic Inverted Half Pyramid with Numbers
In this example, we will print an inverted half pyramid with numbers starting from 1 at the first column, decreasing in length each row.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare an integer variable
rowsand assign it the value of 5 (number of rows in the pyramid). - The outer
forloop runs fromrowsdown to 1, controlling the number of rows. - The inner
forloop prints numbers from1toi, reducingiin each row. - After printing the numbers for each row,
printf("\n")moves the cursor to the next line.
Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
2. Inverted Half Pyramid with Row Numbers
In this example, we will print an inverted half pyramid where each row contains its row number instead of a sequence of numbers.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("%d ", i);
}
printf("\n");
}
return 0;
}
Explanation:
- The
rowsvariable is initialized to5to define the number of rows. - The outer
forloop runs fromrowsto 1. - The inner
forloop prints the row number (i) instead of a sequence of numbers. - The
printf("\n")statement moves to the next row.
Output:
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
3. Inverted Half Pyramid with Reverse Numbers
In this example, we will print an inverted half pyramid where each row contains numbers in descending order.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Explanation:
- The
rowsvariable is set to 5 to determine the number of rows. - The outer loop starts from
rowsand decrements to 1. - The inner loop prints numbers in descending order from
idown to1. - The
printf("\n")ensures a new line after each row.
Output:
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Conclusion
In this tutorial, we learned different ways to print an inverted half-pyramid number pattern in C:
- Printing a basic inverted number pyramid.
- Using row numbers instead of sequential numbers.
- Printing the pyramid with numbers in reverse order.
