16_for2.zig 847 B

123456789101112131415161718192021222324252627
  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. // // Do something with item and index
  7. // }
  8. //
  9. const std = @import("std");
  10. pub fn main() void {
  11. // Let's store the bits of binary number 1101 in
  12. // 'little-endian' order (least significant byte first):
  13. const bits = [_]u8{ 1, 0, 1, 1 };
  14. var value: u32 = 0;
  15. // Now we'll convert the binary bits to a number value by adding
  16. // the value of the place as a power of two for each bit. See if
  17. // you can figure out the missing piece:
  18. //
  19. for (bits) |bit, i| {
  20. var place_value = std.math.pow(u32, 2, @intCast(u32, i));
  21. value += place_value * bit;
  22. }
  23. std.debug.print("The value of bits '1101': {}.\n", .{value});
  24. }