Nesting Loops2:34 with Craig Dennis
You can put loops inside of other loops to create combinations and cross products.
All right, it's hot out there let's do an ice cream example. 0:00 For those of you watching at home, you probably don't know about this place, but 0:04 there is a place here in Portland that likes to make weird ice cream flavors, and 0:07 it mixes sweet and savory, and it's a good combination and so 0:10 I thought this might be a good time. 0:14 It's hot outside, it's really hot today, so let's go make some ice cream 0:15 [INAUDIBLE] you guys [INAUDIBLE] you guys know this song right come on [LAUGH] Okay, 0:19 so, I have two arrays. 0:24 I have a sweet flavor and I have a savory flavor and these are actually real. 0:27 They really do have barbecue sauce and they really do have baked beans. 0:31 So, what we're going to do is we're going to mix these two together. 0:35 And we're going to do that through nesting two for loops. 0:39 So let's go ahead and we'll say, we're gonna use the for each loop here. 0:42 For each of the sweets, the sweet flavors. 0:46 And then we want every single one of the sweet ones to mix with the other ones. 0:50 We wanna see all the possible combinations that we can make with this so 0:53 we're gonna nest the loop. 0:56 So, another for loop. 0:57 So each time, each one of these we're gonna run another one of these loops. 0:59 You see this quite a bit, and sometimes it's using the Is and the Js. 1:01 I keep on pressing tab, I've been moved into the IDE world in writing these 1:06 courses and I've been pressing tab. 1:10 Say %s and %s. 1:15 And we're going to pass in the sweet and we're going to pass in the savory. 1:18 Okay. So let's run it and 1:24 then we'll take a look at, we'll walk it really quick. 1:25 Love that I have a java ice cream. 1:32 Alright. 1:35 Okay, so this is the one that popped out here, this very last one here. 1:39 This is the barbecue sauce. 1:44 And let's see if I can make this actually longer. 1:46 Let's see the whole thing. 1:48 And I'll bring the loop back down. 1:52 Nope, all right, so alright, so 1:53 caramel is the first sweet flavor. 1:58 So what's gonna happen is it's gonna go into this for loop and 2:03 sweet is gonna be set to caramel. 2:05 Next, we're gonna loop through each one of the savory ones but 2:09 we're gonna keep sweet because it's in the top loop. 2:11 And then in the inside loop we're gonna hit savory. 2:13 Does that make sense? 2:17 It happens quite a bit when you need to do cross-products of things and 2:18 combinations of, you want to loop through all of these and 2:21 see what happens if you do a combination with all of these things. 2:24 So it's a nested for loop. 2:27 I just wanted to show you that cause you will see those. 2:28
You need to sign up for Treehouse in order to download course files.Sign up