0
0
Swiftprogramming~30 mins

Labeled statements for nested loops in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Labeled statements for nested loops
📖 Scenario: Imagine you are checking a grid of seats in a theater to find the first empty seat. The seats are arranged in rows and columns.
🎯 Goal: You will write a Swift program that uses labeled statements to break out of nested loops when the first empty seat is found.
📋 What You'll Learn
Create a 2D array called seats representing rows and columns with exact values
Create a label called searchSeats for the outer loop
Use nested for loops to iterate over rows and columns
Use break searchSeats to exit both loops when an empty seat is found
Print the row and column of the first empty seat found
💡 Why This Matters
🌍 Real World
Finding the first available seat in a theater or airplane seating chart is a common real-world task that requires checking nested data structures.
💼 Career
Understanding labeled statements and nested loops helps in writing efficient code for searching and processing multi-dimensional data, useful in software development and data analysis.
Progress0 / 4 steps
1
Create the seats grid
Create a 2D array called seats with these exact values: [["X", "X", "O"], ["X", "O", "X"], ["X", "X", "X"]]. Each "X" means occupied and "O" means empty.
Swift
Need a hint?

Use let seats = [["X", "X", "O"], ["X", "O", "X"], ["X", "X", "X"]] to create the grid.

2
Add the label for the outer loop
Add a label called searchSeats before the outer for loop that iterates over the rows of seats.
Swift
Need a hint?

Write searchSeats: for row in 0.. to label the outer loop.

3
Add nested loop and break with label
Inside the labeled outer loop searchSeats, add an inner for loop with variable col iterating over 0 to seats[row].count. Use if seats[row][col] == "O" to check for an empty seat and then use break searchSeats to exit both loops.
Swift
Need a hint?

Use for col in 0.. and inside it check if seats[row][col] == "O" then break searchSeats.

4
Print the first empty seat position
Add two variables foundRow and foundCol initialized to -1 before the loops. Inside the if seats[row][col] == "O" block, set foundRow = row and foundCol = col before break searchSeats. After the loops, print "First empty seat found at row \(foundRow), column \(foundCol)".
Swift
Need a hint?

Remember to set foundRow = row and foundCol = col before breaking. Then print the message with those variables.