The number-star triangle upside down, starting with the widest row. Below you will see how the pattern is built, followed by complete programs in C, C++, Java and Python.
This program is part of the Number-Star Patterns collection.
Inverted Number-Star Triangle output
Output (n = 5):
5*5*5*5*5 4*4*4*4 3*3*3 2*2 1

How the inverted number-star triangle works
The same row rule as the number-star triangle, with i counting down from n to 1.
- Run the outer loop for
ifromndown to1, one row per pass. - Go through
2 × i − 1positions in the row. Print numbers (valuei) wherej % 2 = 1; print stars everywhere else. - Move to the next line.
Inverted Number-Star Triangle in C
#include <stdio.h>
int main(void) {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= 2 * i - 1; j++) {
if (j % 2 == 1)
printf("%d", i);
else
printf("*");
}
printf("\n");
}
return 0;
}Inverted Number-Star Triangle in C++
#include <iostream>
using namespace std;
int main() {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= 2 * i - 1; j++) {
if (j % 2 == 1)
cout << i;
else
cout << "*";
}
cout << endl;
}
return 0;
}Inverted Number-Star Triangle in Java
public class InvertedNumberStarTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= 2 * i - 1; j++) {
if (j % 2 == 1)
System.out.print(i);
else
System.out.print("*");
}
System.out.println();
}
}
}Inverted Number-Star Triangle in Python
n = 5
for i in range(n, 0, -1):
for j in range(1, 2 * i):
if j % 2 == 1:
print(i, end="")
else:
print("*", end="")
print()Time and space complexity
The program prints one character for each position in the pattern, so for n rows it runs in O(n²) time. It only needs a few loop variables, so the extra memory is O(1).





