016_for2.zig 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // For loops also let you use the "index" of the iteration, a number
  3. // that counts up with each iteration. To access the index of iteration,
  4. // specify a second condition as well as a second capture value.
  5. //
  6. // for (items, 0..) |item, index| {
  7. //
  8. // // Do something with item and index
  9. //
  10. // }
  11. //
  12. // You can name "item" and "index" anything you want. "i" is a popular
  13. // shortening of "index". The item name is often the singular form of
  14. // the items you're looping through.
  15. //
  16. const std = @import("std");
  17. pub fn main() void {
  18. // Let's store the bits of binary number 1101 in
  19. // 'little-endian' order (least significant byte or bit first):
  20. const bits = [_]u8{ 1, 0, 1, 1 };
  21. var value: u32 = 0;
  22. // Now we'll convert the binary bits to a number value by adding
  23. // the value of the place as a power of two for each bit.
  24. //
  25. // See if you can figure out the missing pieces:
  26. for (bits, ???) |bit, ???| {
  27. // Note that we convert the usize i to a u32 with
  28. // @intCast(), a builtin function just like @import().
  29. // We'll learn about these properly in a later exercise.
  30. const place_value = std.math.pow(u32, 2, @intCast(u32, i));
  31. value += place_value * bit;
  32. }
  33. std.debug.print("The value of bits '1101': {}.\n", .{value});
  34. }
  35. //
  36. // As mentioned in the previous exercise, 'for' loops have gained
  37. // additional flexibility since these early exercises were
  38. // written. As we'll see in later exercises, the above syntax for
  39. // capturing the index is part of a more general ability. Hang in
  40. // there!