To print a rhombus pattern in Swift, you can use nested loops to control the number of spaces and asterisks printed on each line. The pattern is symmetrical and consists of an upper and lower part.
In this example,
n
with a value of 5
, which represents the height of the rhombus.for
loop to iterate from 1
to n
. This loop controls the number of rows in the upper part of the rhombus.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 rhombus is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to n
, which creates the width of the rhombus.row
string, which represents the current row of the upper part of the rhombus.for
loop to iterate from 1
to n-1
.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 i
, where i
is the current row number. This ensures that the rhombus is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to n
, which creates the width of the rhombus.row
string, which represents the current row of the lower part of the rhombus.let n = 5
for i in 1...n {
var row = ""
for _ in 0..<(n - i) {
row += " "
}
for _ in 0..<n {
row += "*"
}
print(row)
}
for i in 1..<n {
var row = ""
for _ in 0..<i {
row += " "
}
for _ in 0..<n {
row += "*"
}
print(row)
}
***** ***** ***** ***** ***** ***** ***** ***** *****
In this example,
n
with a value of 3
, which represents the height of the rhombus.for
loop to iterate from 1
to n
. This loop controls the number of rows in the upper part of the rhombus.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 rhombus is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to n
, which creates the width of the rhombus.row
string, which represents the current row of the upper part of the rhombus.for
loop to iterate from 1
to n-1
.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 i
, where i
is the current row number. This ensures that the rhombus is centered.for
loop to add asterisks to the row
string. The number of asterisks is equal to n
, which creates the width of the rhombus.row
string, which represents the current row of the lower part of the rhombus.let n = 3
for i in 1...n {
var row = ""
for _ in 0..<(n - i) {
row += " "
}
for _ in 0..<n {
row += "*"
}
print(row)
}
for i in 1..<n {
var row = ""
for _ in 0..<i {
row += " "
}
for _ in 0..<n {
row += "*"
}
print(row)
}
*** *** *** *** ***
In this tutorial, we learned How to print Rhombus Pattern in Swift language with well detailed examples.