020_quiz3.zig 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // Let's see if we can make use of some of things we've learned so far.
  3. // We'll create two functions: one that contains a "for" loop and one
  4. // that contains a "while" loop.
  5. //
  6. // Both of these are simply labeled "loop" below.
  7. //
  8. const std = @import("std");
  9. pub fn main() void {
  10. const my_numbers = [4]u16{ 5, 6, 7, 8 };
  11. printPowersOfTwo(my_numbers);
  12. std.debug.print("\n", .{});
  13. }
  14. // You won't see this every day: a function that takes an array with
  15. // exactly four u16 numbers. This is not how you would normally pass
  16. // an array to a function. We'll learn about slices and pointers in
  17. // a little while. For now, we're using what we know.
  18. //
  19. // This function prints, but does not return anything.
  20. //
  21. fn printPowersOfTwo(numbers: [4]u16) ??? {
  22. loop (numbers) |n| {
  23. std.debug.print("{} ", .{twoToThe(n)});
  24. }
  25. }
  26. // This function bears a striking resemblance to twoToThe() in the last
  27. // exercise. But don't be fooled! This one does the math without the aid
  28. // of the standard library!
  29. //
  30. fn twoToThe(number: u16) ??? {
  31. var n: u16 = 0;
  32. var total: u16 = 1;
  33. loop (n < number) : (n += 1) {
  34. total *= 2;
  35. }
  36. return ???;
  37. }