20_quiz3.zig 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. //
  15. // You won't see this every day: a function that takes an array with
  16. // exactly four u16 numbers. This is not how you would normally pass
  17. // an array to a function. We'll learn about slices and pointers in
  18. // a little while. For now, we're using what we know.
  19. //
  20. // This function prints, but does not return anything.
  21. //
  22. fn printPowersOfTwo(numbers: [4]u16) ??? {
  23. loop (numbers) |n| {
  24. std.debug.print("{} ", .{twoToThe(n)});
  25. }
  26. }
  27. //
  28. // This function bears a striking resemblance to twoToThe() in the last
  29. // exercise. But don't be fooled! This one does the math without the aid
  30. // of the standard library!
  31. //
  32. fn twoToThe(number: u16) ??? {
  33. var n: u16 = 0;
  34. var total: u16 = 1;
  35. loop (n < number) : (n += 1) {
  36. total *= 2;
  37. }
  38. return ???;
  39. }