top of page
Home: Blog2
Home: Instagram_Widget

Nested for loops

A nested loop is basically a loop within a loop.I couldn't figure out why I want to use this kind of a loop but then it dawned on me that if there were multiple arrays then I could use this kind of a nested loop to sort of iterate over and over again.


So lets try it out in practice. I am assuming that I have 3 arrays here and each array has bits of information which need to be combined. The arrays comprise of the bus number, hours of service and the minutes with the hour when the bus will arrive


var busNumber: [String] = ["747", "905"]
var frequencyHours: [String] = ["09", "10", "11"]
var frequencyMinutes: [String] = [":15 Hrs",":45 Hrs"]


for (_, busNumber) in busNumber.enumerated() {
 for (_, frequencyHours) in frequencyHours.enumerated() {
 for (_, frequencyMinutes) in frequencyMinutes.enumerated() {
 print("Bus \(busNumber) arrives at \(frequencyHours)\(frequencyMinutes) ")
 
 }
 }
}

Here, the (_, frequencyMinutes) infrequencyMinutes.enumerated() loop known as inner loop, is inside the body of known as outer loop for (_, busNumber) inbusNumber.enumerated(). the output from the code would give us


Bus 747 arrives at 09:15 Hrs 
Bus 747 arrives at 09:45 Hrs 
Bus 747 arrives at 10:15 Hrs 
Bus 747 arrives at 10:45 Hrs 
Bus 747 arrives at 11:15 Hrs 
Bus 747 arrives at 11:45 Hrs 
Bus 905 arrives at 09:15 Hrs 
Bus 905 arrives at 09:45 Hrs 
Bus 905 arrives at 10:15 Hrs 
Bus 905 arrives at 10:45 Hrs 
Bus 905 arrives at 11:15 Hrs 
Bus 905 arrives at 11:45 Hrs 

it should be noted that its possible to similarly adopt nested loops for a while loop as well. More to follow on that in the next series of posts on while loops.

Comments


Home: Subscribe

©2019 by CodingWithSuj. Proudly created with Wix.com

bottom of page