Skip to content

Exercises

1. Write a function max3 that returns the largest of three integers.

  1. Write a function max3 that returns the largest of three integers.

  2. Write a function minSlice that returns the smallest element of a slice of integers.

  3. Write a function count that counts how many times a byte appears in a string.

  4. Write a function reverse that reverses a slice in place using pointers.

  5. Write a module temperature.zig with public functions:

celsiusToFahrenheit
fahrenheitToCelsius
  1. Write a function:
fn swap(a: *i32, b: *i32) void

that exchanges two integers.

  1. Write a function that returns both quotient and remainder using a struct:
const Result = struct {
    quotient: i32,
    remainder: i32,
};
  1. Write a function contains that checks whether a slice contains a given value.

  2. Write a program split across files:

main.zig
math.zig
stats.zig

where main.zig imports the others.

  1. Write a module with one public function and several private helper functions.

  2. Write a function that modifies every element of a slice through a pointer.

  3. What is the difference between:

i32

and:

*i32

when used as function parameters?

  1. Explain why this function is unsafe:
fn bad() *i32 {
    var x: i32 = 0;
    return &x;
}
  1. Write a function that accepts:
[]const u8

and prints the string.

  1. Write a function that returns an optional integer:
?i32

Return null if division by zero occurs.

  1. Organize a small project into modules with clearly separated responsibilities.

  2. Write a function map that applies another function to every element of a slice.

  3. Write a function that computes the average of a slice of floating-point values.

  4. Write a module vector.zig containing:

Vec2
add
sub
scale
dot
  1. Rewrite a long function into smaller functions with clearer names.

  2. Design a public interface for a parser module. Decide which declarations should remain private.

  3. Write a function that receives a struct by pointer and modifies one field.

  4. Explain why explicit imports help avoid namespace collisions.

  5. Write a small command-line calculator using multiple source files.