⚡ TL;DR
Print the inverted right triangle star pattern in Swift. Complete working code, expected output, algorithm explanation, and practice variations for beginners.
The Inverted Right Triangle Star pattern is a fundamental loop exercise for Swift beginners. Here’s the complete implementation with working code and output.
Pattern to Print
*****
****
***
**
*Implementation
func invertedTriangle(_ n: Int) {
for i in stride(from: n, through: 1, by: -1) {
print(String(repeating: "*", count: i))
}
}
invertedTriangle(5)Output
*****
****
***
**
*How It Works
Decreasing stars per row — loop from n down to 1.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a diamond or hourglass
Complexity
- Time: O(n²) — total characters printed grows quadratically
- Space: O(n) — longest row is O(n) characters
Related Patterns
- Inverted Right Triangle Star in Python
- Inverted Right Triangle Star in Dart
- Inverted Right Triangle Star in Go
FAQ
How do you print the Inverted Right Triangle Star pattern in Swift?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Swift implementation with expected output is shown in the sections above.
What is the time complexity of the Inverted Right Triangle Star pattern in Swift?
The time complexity is O(n²) and the space complexity is O(n), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
