|
| 1 | +// |
| 2 | +// We've seen that the 'for' loop can let us perform some action |
| 3 | +// for every item in an array or slice. |
| 4 | +// |
| 5 | +// More recently, we discovered that it supports ranges to |
| 6 | +// iterate over number sequences. |
| 7 | +// |
| 8 | +// This is part of a more general capability of the `for` loop: |
| 9 | +// looping over one or more "objects" where an object is an |
| 10 | +// array, slice, or range. |
| 11 | +// |
| 12 | +// In fact, we *did* use multiple objects way back in Exercise |
| 13 | +// 016 where we iterated over an array and also a numeric index. |
| 14 | +// It didn't always work exactly this way, so the exercise had to |
| 15 | +// be retroactively modified a little bit. |
| 16 | +// |
| 17 | +// for (bits, 0..) |bit, i| { ... } |
| 18 | +// |
| 19 | +// The general form of a 'for' loop with two lists is: |
| 20 | +// |
| 21 | +// for (list_a, list_b) |a, b| { |
| 22 | +// // Here we have the first item from list_a and list_b, |
| 23 | +// // then the second item from each, then the third and |
| 24 | +// // so forth... |
| 25 | +// } |
| 26 | +// |
| 27 | +// What's really beautiful about this is that we don't have to |
| 28 | +// keep track of an index or advancing a memory pointer for |
| 29 | +// *either* of these lists. That error-prone stuff is all taken |
| 30 | +// care of for us by the compiler. |
| 31 | +// |
| 32 | +// Below, we have a program that is supposed to compare two |
| 33 | +// arrays. Please make it work! |
| 34 | +// |
| 35 | +const std = @import("std"); |
| 36 | +const print = std.debug.print; |
| 37 | + |
| 38 | +pub fn main() void { |
| 39 | + const hex_nums = [_]u8{ 0xb, 0x2a, 0x77 }; |
| 40 | + const dec_nums = [_]u8{ 11, 42, 119 }; |
| 41 | + |
| 42 | + for (hex_nums, ???) |hn, ???| { |
| 43 | + if (hn != dn) { |
| 44 | + std.debug.print("Uh oh! Found a mismatch: {d} vs {d}\n", .{ hn, dn }); |
| 45 | + return; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + std.debug.print("Arrays match!\n", .{}); |
| 50 | +} |
| 51 | +// |
| 52 | +// You are perhaps wondering what happens if one of the two lists |
| 53 | +// is longer than the other? Try it! |
| 54 | +// |
| 55 | +// By the way, congratulations for making it to Exercise 100! |
| 56 | +// |
| 57 | +// +-------------+ |
| 58 | +// | Celebration | |
| 59 | +// | Area * * * | |
| 60 | +// +-------------+ |
| 61 | +// |
| 62 | +// Please keep your celebrating within the area provided. |
0 commit comments