100_for4.zig 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. pub fn main() void {
  38. const hex_nums = [_]u8{ 0xb, 0x2a, 0x77 };
  39. const dec_nums = [_]u8{ 11, 42, 119 };
  40. for (hex_nums, ???) |hn, ???| {
  41. if (hn != dn) {
  42. print("Uh oh! Found a mismatch: {d} vs {d}\n", .{ hn, dn });
  43. return;
  44. }
  45. }
  46. print("Arrays match!\n", .{});
  47. }
  48. //
  49. // You are perhaps wondering what happens if one of the two lists
  50. // is longer than the other? Try it!
  51. //
  52. // By the way, congratulations for making it to Exercise 100!
  53. //
  54. // +-------------+
  55. // | Celebration |
  56. // | Area * * * |
  57. // +-------------+
  58. //
  59. // Please keep your celebrating within the area provided.