Skip to content

Exercises

This section closes the chapter. The exercises are small programs. Write them by hand. Compile them. Change them. Run them again.

This section closes the chapter. The exercises are small programs. Write them by hand. Compile them. Change them. Run them again.

Exercise 6-1. Declare an array of 10 integers and print the elements in order.

Exercise 6-2. Print the same array in reverse order.

Exercise 6-3. Write a function named zero5 that takes *[5]i32 and sets all five elements to zero.

Exercise 6-4. Copy one array to another. Change the second array. Print both arrays to show that the copy is separate.

Exercise 6-5. Declare this array with an inferred length:

const nums = [_]i32{ 1, 2, 3, 4, 5 };

Print its length.

Exercise 6-6. Create an array of 16 zero bytes using **.

Exercise 6-7. Create a 3 by 3 table of integers. Print the value in row 2, column 1.

Exercise 6-8. Write a function sum that takes []const i32 and returns the sum.

Exercise 6-9. Write a function fill that takes []i32 and an i32 value, and sets every element of the slice to that value.

Exercise 6-10. Create an array of 8 integers. Make a slice containing elements 2 through 5. Change the slice. Print the original array.

Exercise 6-11. Declare a sentinel array:

const word: [5:0]u8 = .{ 'h', 'e', 'l', 'l', 'o' };

Convert it to [:0]const u8 and print it with {s}.

Exercise 6-12. Print every byte of "zig" as a decimal number.

Exercise 6-13. Print every byte of "é" as a hexadecimal number.

Exercise 6-14. Use std.unicode.Utf8View to print the code points of "hé".

Exercise 6-15. Write a function countCodepoints that takes []const u8 and returns !usize.

Exercise 6-16. Explain, in one sentence, the difference between [N]T and []T.

Exercise 6-17. Explain, in one sentence, why s.len is not always the number of characters in a string.

Exercise 6-18. Write a program that accepts one string literal, prints its byte length, then prints its UTF-8 code point count.