⚡ TL;DR
Print the floyd's triangle pattern in Swift. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Floyd’s Triangle pattern is a classic loop exercise. Here’s the complete implementation in Swift with working code and output.
Pattern to Print
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15Implementation
func floydsTriangle(_ n: Int) {
var num = 1
for i in 1...n {
var row = ""
for _ in 0..<i { row += "(num) "; num += 1 }
print(row)
}
}
floydsTriangle(5)Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15How It Works
A single counter increments with every printed number. Row i contains i numbers.
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 more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
Related Patterns
- Floyd’s Triangle in Python
- Floyd’s Triangle in Dart
- Floyd’s Triangle in Go
- Pascal’s Triangle in Swift
- Palindromic Number Pyramid in Swift
- Number Pyramid in Swift
FAQ
How do you print the Floyd’s Triangle 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 Floyd’s Triangle pattern in Swift?
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!
