095_for_loops.zig 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // The Zig language is in rapid development and continuously
  3. // improves the language constructs. Ziglings evolves with it.
  4. //
  5. // Until version 0.11, Zig's 'for' loops did not directly
  6. // replicate the functionality of the C-style: "for(a;b;c)"
  7. // which are so well suited for iterating over a numeric
  8. // sequence.
  9. //
  10. // Instead, 'while' loops with counters clumsily stood in their
  11. // place:
  12. //
  13. // var i: usize = 0;
  14. // while (i < 10) : (i += 1) {
  15. // // Here variable 'i' will have each value 0 to 9.
  16. // }
  17. //
  18. // But here we are in the glorious future and Zig's 'for' loops
  19. // can now take this form:
  20. //
  21. // for (0..10) |i| {
  22. // // Here variable 'i' will have each value 0 to 9.
  23. // }
  24. //
  25. // The key to understanding this example is to know that '0..9'
  26. // uses the new range syntax:
  27. //
  28. // 0..10 is a range from 0 to 9
  29. // 1..4 is a range from 1 to 3
  30. //
  31. // At the moment, ranges are only supported in 'for' loops.
  32. //
  33. // Perhaps you recall Exercise 13? We were printing a numeric
  34. // sequence like so:
  35. //
  36. // var n: u32 = 1;
  37. //
  38. // // I want to print every number between 1 and 20 that is NOT
  39. // // divisible by 3 or 5.
  40. // while (n <= 20) : (n += 1) {
  41. // // The '%' symbol is the "modulo" operator and it
  42. // // returns the remainder after division.
  43. // if (n % 3 == 0) continue;
  44. // if (n % 5 == 0) continue;
  45. // std.debug.print("{} ", .{n});
  46. // }
  47. //
  48. // Let's try out the new form of 'for' to re-implement that
  49. // exercise:
  50. //
  51. const std = @import("std");
  52. pub fn main() void {
  53. // I want to print every number between 1 and 20 that is NOT
  54. // divisible by 3 or 5.
  55. for (???) |n| {
  56. // The '%' symbol is the "modulo" operator and it
  57. // returns the remainder after division.
  58. if (n % 3 == 0) continue;
  59. if (n % 5 == 0) continue;
  60. std.debug.print("{} ", .{n});
  61. }
  62. std.debug.print("\n", .{});
  63. }
  64. //
  65. // That's a bit nicer, right?
  66. //
  67. // Of course, both 'while' and 'for' have different advantages.
  68. // Exercises 11, 12, and 14 would NOT be simplified by switching
  69. // a 'while' for a 'for'.