016_for2.zig 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. //
  2. // For loops also let you store the "index" of the iteration - a
  3. // number starting with 0 that counts up with each iteration:
  4. //
  5. // for (items) |item, index| {
  6. //
  7. // // Do something with item and index
  8. //
  9. // }
  10. //
  11. // You can name "item" and "index" anything you want. "i" is a popular
  12. // shortening of "index". The item name is often the singular form of
  13. // the items you're looping through.
  14. //
  15. const std = @import("std");
  16. pub fn main() void {
  17. // Let's store the bits of binary number 1101 in
  18. // 'little-endian' order (least significant byte first):
  19. const bits = [_]u8{ 1, 0, 1, 1 };
  20. var value: u32 = 0;
  21. // Now we'll convert the binary bits to a number value by adding
  22. // the value of the place as a power of two for each bit.
  23. //
  24. // See if you can figure out the missing piece:
  25. for (bits) |bit, ???| {
  26. var place_value = std.math.pow(u32, 2, @intCast(u32, i));
  27. value += place_value * bit;
  28. }
  29. std.debug.print("The value of bits '1101': {}.\n", .{value});
  30. }