095_for_loops.zig 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // The Zig language is in rapid development and continuously improves
  3. // the language constructs steadily.
  4. //
  5. // Since version 0.11, the "for-loops" widely used in other languages
  6. // such as C, e.g. "for (int i = 0; i < 10..." can now also be formed
  7. // similarly in Zig, which previously required a "while" construct.
  8. // Similar in this case actually means better, just as Zig generally
  9. // tries to make everything simple and "better".
  10. //
  11. // These new "for-loops" look like the following in Zig:
  12. //
  13. // for (0..10) |idx| {
  14. // // In this case 'idx' takes all values from 0 to 9.
  15. // }
  16. //
  17. // This is really simple and can replace the previous, somewhat bulky:
  18. //
  19. // var idx: usize = 0;
  20. // while (idx < 10) : (idx += 1) {
  21. // // Again, idx takes all values from 0 to 9.
  22. // }
  23. //
  24. // This would also simplify exercise 13, for example.
  25. // The best way to try this out is to use this exercise, which in the
  26. // original looks like this:
  27. //
  28. // ...
  29. // var n: u32 = 1;
  30. //
  31. // // I want to print every number between 1 and 20 that is NOT
  32. // // divisible by 3 or 5.
  33. // while (n <= 20) : (n += 1) {
  34. // // The '%' symbol is the "modulo" operator and it
  35. // // returns the remainder after division.
  36. // if (n % 3 == 0) continue;
  37. // if (n % 5 == 0) continue;
  38. // std.debug.print("{} ", .{n});
  39. // }
  40. // ...
  41. //
  42. const std = @import("std");
  43. // And now with the new "for-loop".
  44. pub fn main() void {
  45. // I want to print every number between 1 and 20 that is NOT
  46. // divisible by 3 or 5.
  47. for (???) |n| {
  48. // The '%' symbol is the "modulo" operator and it
  49. // returns the remainder after division.
  50. if (n % 3 == 0) continue;
  51. if (n % 5 == 0) continue;
  52. std.debug.print("{} ", .{n});
  53. }
  54. std.debug.print("\n", .{});
  55. }
  56. // Is actually a little easier. The interesting thing here is that the other
  57. // previous 'while' exercises (11,12, 14) cannot be simplified by this
  58. // new "for-loop". Therefore it is good to be able to use both variations
  59. // accordingly.