Swift Nested Loops
🔁🔁 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
📌 Inner loop executes multiple times for one outer loop iteration.
2️⃣ Simple Nested for Loop ⭐
Output
3️⃣ Nested Loop – Number Pattern ⭐⭐
Example: Square Pattern
Output
4️⃣ Nested Loop – Number Triangle ⭐⭐
Output
5️⃣ Multiplication Table Using Nested Loop ⭐⭐
Output
6️⃣ Nested while Loop ⭐⭐
Output
7️⃣ Nested repeat-while Loop ⭐⭐
Output
8️⃣ Using break and continue in Nested Loops ⭐⭐⭐
break (breaks inner loop)
Output
continue (skips current iteration)
Output
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
