016_for2.zig 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 i_u32: u32 = @intCast(i);
  31. const place_value = std.math.pow(u32, 2, i_u32);
  32. value += place_value * bit;
  33. }
  34. std.debug.print("The value of bits '1101': {}.\n", .{value});
  35. }
  36. //
  37. // As mentioned in the previous exercise, 'for' loops have gained
  38. // additional flexibility since these early exercises were
  39. // written. As we'll see in later exercises, the above syntax for
  40. // capturing the index is part of a more general ability. Hang in
  41. // there!