How to print Pyramid Pattern in Swift - Step by Step Examples
How to print Pyramid Pattern in Swift ?
Answer
To print a pyramid pattern in Swift, you can use nested loops to control the number of spaces and asterisks printed on each line. The outer loop controls the rows, while the inner loops control the spaces and asterisks for each row.
✐ Examples
1 Pyramid pattern of height 5
In this example,
- We start by defining a constant
n
with a value of5
, which represents the height of the pyramid. - Next, we use a
for
loop to iterate from1
ton
. This loop controls the number of rows in the pyramid. - Within the outer loop, we initialize an empty string
row
to build the content of the current row. - We then use another
for
loop to add spaces to therow
string. The number of spaces is equal ton - i
, wherei
is the current row number. This ensures that the pyramid is centered. - After adding the spaces, we use another
for
loop to add asterisks to therow
string. The number of asterisks is equal to2 * i - 1
, which creates the pyramid shape. - We then print the
row
string, which represents the current row of the pyramid.
Swift Program
let n = 5
for i in 1...n {
var row = ""
for _ in 0..<(n - i) {
row += " "
}
for _ in 0..<(2 * i - 1) {
row += "*"
}
print(row)
}
Output
* *** ***** ******* *********
2 Pyramid pattern of height 3
In this example,
- We start by defining a constant
n
with a value of3
, which represents the height of the pyramid. - Next, we use a
for
loop to iterate from1
ton
. This loop controls the number of rows in the pyramid. - Within the outer loop, we initialize an empty string
row
to build the content of the current row. - We then use another
for
loop to add spaces to therow
string. The number of spaces is equal ton - i
, wherei
is the current row number. This ensures that the pyramid is centered. - After adding the spaces, we use another
for
loop to add asterisks to therow
string. The number of asterisks is equal to2 * i - 1
, which creates the pyramid shape. - We then print the
row
string, which represents the current row of the pyramid.
Swift Program
let n = 3
for i in 1...n {
var row = ""
for _ in 0..<(n - i) {
row += " "
}
for _ in 0..<(2 * i - 1) {
row += "*"
}
print(row)
}
Output
* *** *****
Summary
In this tutorial, we learned How to print Pyramid Pattern in Swift language with well detailed examples.
More Swift Pattern Printing Tutorials
- How to print Left Half Pyramid Pattern in Swift ?
- How to print Right Half Pyramid Pattern in Swift ?
- How to print Pyramid Pattern in Swift ?
- How to print Rhombus Pattern in Swift ?
- How to print Diamond Pattern in Swift ?
- How to print Hour Glass Pattern in Swift ?
- How to print Hollow Square Pattern in Swift ?
- How to print Hollow Pyramid Pattern in Swift ?
- How to print Hollow Inverted Pyramid Pattern in Swift ?
- How to print Hollow Diamond Pattern in Swift ?
- How to print Floyd's Trianlge Pattern in Swift ?
- How to print Pascal's Triangle Pattern in Swift ?