015_for.zig 813 B

1234567891011121314151617181920212223242526272829303132
  1. //
  2. // Behold the 'for' loop! For loops let you execute code for each
  3. // element of an array:
  4. //
  5. // for (items) |item| {
  6. //
  7. // // Do something with item
  8. //
  9. // }
  10. //
  11. const std = @import("std");
  12. pub fn main() void{
  13. const story = [_]u8{ 'h', 'h', 's', 'n', 'h' };
  14. std.debug.print("A Dramatic Story: ", .{});
  15. for(story) |scene|{
  16. if(scene == 'h'){ std.debug.print(":-) ", .{}); }
  17. if(scene == 's'){ std.debug.print(":-( ", .{}); }
  18. if(scene == 'n'){ std.debug.print(":-| ", .{}); }
  19. }
  20. std.debug.print("The End.\n", .{});
  21. }
  22. // Note that 'for' loops also work on things called "slices"
  23. // which we'll see later.
  24. //
  25. // Also note that 'for' loops have recently become more flexible
  26. // and powerful (two years after this exercise was written).
  27. // More about that in a moment.