⚡ TL;DR
Print an inverted right-angle triangle star pattern in Dart with full example code, three variations, and common beginner mistakes explained.
The inverted right triangle pattern is the reverse of the classic right-angled triangle. It teaches you Dart’s descending loop range and how to reduce star count row by row.
What We’ll Build
*****
****
***
**
*Each row has one fewer star than the row above.
Approach 1: Loop from N Down to 1
void main() {
int n = 5;
for (int i = n; i >= 1; i--) {
String row = "";
for (int j = 1; j <= i; j++) {
row += "*";
}
print(row);
}
}Output
*****
****
***
**
*Approach 2: String Multiplication (More Idiomatic)
void main() {
int n = 5;
for (int i = n; i >= 1; i--) {
print("*" * i);
}
}Output
*****
****
***
**
*Approach 3: Using List.generate
void main() {
int n = 5;
for (int i = n; i >= 1; i--) {
print(List.generate(i, (_) => "*").join());
}
}Variation: With Trailing Spaces (Mirrored)
void main() {
int n = 5;
for (int i = 0; i < n; i++) {
print(" " * i + "*" * (n - i));
}
}Output
*****
****
***
**
*Approach 4: Using Iterable.generate
void main() {
int n = 5;
Iterable<int>.generate(n, (i) => n - i).forEach((count) {
print("*" * count);
});
}Common Beginner Mistakes
- Using
i++instead ofi--— the pattern increases instead of decreasing - Off-by-one in the loop bound —
i > 0vsi >= 1matters - String immutability confusion —
Stringin Dart is immutable;StringBufferis better for building
Performance Note
// ❌ Slow — O(n³) due to String copies
for (int i = n; i >= 1; i--) {
String row = "";
for (int j = 1; j <= i; j++) {
row += "*"; // Creates new String object each time
}
print(row);
}
// ✅ Fast — O(n²) with StringBuffer
for (int i = n; i >= 1; i--) {
StringBuffer row = StringBuffer();
for (int j = 1; j <= i; j++) {
row.write("*");
}
print(row.toString());
}Complexity Analysis
- Time: O(n²) — total stars printed = n + (n-1) + … + 1 = n(n+1)/2
- Space: O(n) — longest row is
ncharacters
Practice Variations
- Diamond: inverted pyramid + pyramid
- Number triangle:
54321 \n 5432 \n 543 - Character triangle:
EDCBA \n EDCB \n EDC - Sandglass: inverted pyramid + pyramid
Next Patterns to Try
Related Patterns
- Inverted Right Triangle Star in Python
- Inverted Right Triangle Star in Go
- Inverted Right Triangle Star in Swift
FAQ
How do you print the Inverted Right Triangle Star pattern in Dart?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Dart implementation with expected output is shown in the sections above.
What is the time complexity of the Inverted Right Triangle Star pattern in Dart?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
