04_arrays.zig 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // Let's learn some array basics. Arrays are declared with:
  3. //
  4. // var foo [3]u32 = [3]u32{ 42, 108, 5423 };
  5. //
  6. // When Zig can infer the size of the array, you can use '_' for the
  7. // size. You can also let Zig infer the type of the value so the
  8. // declaration is much less verbose.
  9. //
  10. // var foo = [_]u32{ 42, 108, 5423 };
  11. //
  12. // Get values of an array using array[index] notation:
  13. //
  14. // const bar = foo[3]; // 5423
  15. //
  16. // Set values of an array using array[index] notation:
  17. //
  18. // foo[3] = 16;
  19. //
  20. // Get the length of an array using the len property:
  21. //
  22. // const length = foo.len;
  23. //
  24. const std = @import("std");
  25. pub fn main() void {
  26. // (Problem 1)
  27. // This "const" is going to cause a problem later - can you see what it is?
  28. // How do we fix it?
  29. const some_primes = [_]u8{ 1, 3, 5, 7, 11, 13, 17, 19 };
  30. // Individual values can be set with '[]' notation.
  31. // Example: This line changes the first prime to 2 (which is correct):
  32. some_primes[0] = 2;
  33. // Individual values can also be accessed with '[]' notation.
  34. // Example: This line stores the first prime in "first":
  35. const first = some_primes[0];
  36. // (Problem 2)
  37. // Looks like we need to complete this expression. Use the example
  38. // above to set "fourth" to the fourth element of the some_primes array:
  39. const fourth = some_primes[???];
  40. // (Problem 3)
  41. // Use the len property to get the length of the array:
  42. const length = some_primes.???;
  43. std.debug.print("First: {}, Fourth: {}, Length: {}\n",
  44. .{first, fourth, length});
  45. }