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.
In this example,
n
with a value of 5
, which represents the height of the pyramid.for
loop to iterate from 1
to n
. This loop controls the number of rows in the pyramid.row
to build the content of the current row.for
loop to add spaces to the row
string. The number of spaces is equal to n - i
, where i
is the current row number. This ensures that the pyramid is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to 2 * i - 1
, which creates the pyramid shape.row
string, which represents the current row of the pyramid.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)
}
* *** ***** ******* *********
In this example,
n
with a value of 3
, which represents the height of the pyramid.for
loop to iterate from 1
to n
. This loop controls the number of rows in the pyramid.row
to build the content of the current row.for
loop to add spaces to the row
string. The number of spaces is equal to n - i
, where i
is the current row number. This ensures that the pyramid is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to 2 * i - 1
, which creates the pyramid shape.row
string, which represents the current row of the pyramid.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)
}
* *** *****
In this tutorial, we learned How to print Pyramid Pattern in Swift language with well detailed examples.