Swift Nested Loops

Swift Nested Loops

Place a loop inside another loop to generate combinations or matrices.


Generate combinations with nested loops

Use inner and outer loops to produce pairs or grids from ranges and collections.

Example

for i in 1...2 {
  for j in 1...3 {
print(i, j)
} }


Multiplication Table

Use nested loops to build a small multiplication table.

Example

for i in 1...3 {
  var row = ""
  for j in 1...3 {
row += "\(i*j) "
} print(row) }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *