Swift Nested Loops

Swift Tutorial

🔁🔁 Swift Nested Loops – Complete Beginner to Interview Guide

In Swift, nested loops mean one loop placed inside another loop.
They are mainly used for patterns, tables, matrices, and multi-dimensional data.


1️⃣ What are Nested Loops in Swift? ⭐

  • A loop inside another loop

  • Inner loop runs completely for each iteration of the outer loop

General Syntax

for outer in range {
for inner in range {
// code
}
}

📌 Inner loop executes multiple times for one outer loop iteration.


2️⃣ Simple Nested for Loop ⭐


Output

i = 1 j = 1
i = 1 j = 2
i = 2 j = 1
i = 2 j = 2
i = 3 j = 1
i = 3 j = 2

3️⃣ Nested Loop – Number Pattern ⭐⭐

Example: Square Pattern


Output

* * *
* * *
* * *

4️⃣ Nested Loop – Number Triangle ⭐⭐


Output

1
1 2
1 2 3
1 2 3 4

5️⃣ Multiplication Table Using Nested Loop ⭐⭐


Output

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15

6️⃣ Nested while Loop ⭐⭐


 

Output

i = 1 j = 1
i = 1 j = 2
i = 2 j = 1
i = 2 j = 2
i = 3 j = 1
i = 3 j = 2

7️⃣ Nested repeat-while Loop ⭐⭐


 

Output

1 1
1 2
2 1
2 2
3 1
3 2

8️⃣ Using break and continue in Nested Loops ⭐⭐⭐

break (breaks inner loop)


Output

1 1
2 1
3 1

continue (skips current iteration)


Output

1 1
1 3
2 1
2 3
3 1
3 3

9️⃣ Common Mistakes ❌

❌ Forgetting to reset inner loop variable
❌ Creating infinite nested loops
❌ Too many nested levels (slow & hard to read)
❌ Using nested loops where one loop is enough


📌 Interview Questions

Q1. What are nested loops?
👉 A loop inside another loop

Q2. How many times does inner loop run?
👉 Completely for each outer loop iteration

Q3. Where are nested loops used?
👉 Patterns, tables, matrices, grids


✅ Summary

✔ Nested loops = loop inside loop
✔ Inner loop runs fully each time
✔ Used for patterns & tables
✔ Works with for, while, repeat-while
✔ Important for Swift exams & interviews

You may also like...