Exercises
1. Write a function max3 that returns the largest of three integers.
Exercises
-
Write a function
max3that returns the largest of three integers. -
Write a function
minSlicethat returns the smallest element of a slice of integers. -
Write a function
countthat counts how many times a byte appears in a string. -
Write a function
reversethat reverses a slice in place using pointers. -
Write a module
temperature.zigwith public functions:
celsiusToFahrenheit
fahrenheitToCelsius
- Write a function:
fn swap(a: *i32, b: *i32) void
that exchanges two integers.
- Write a function that returns both quotient and remainder using a struct:
const Result = struct {
quotient: i32,
remainder: i32,
};
-
Write a function
containsthat checks whether a slice contains a given value. -
Write a program split across files:
main.zig
math.zig
stats.zig
where main.zig imports the others.
-
Write a module with one public function and several private helper functions.
-
Write a function that modifies every element of a slice through a pointer.
-
What is the difference between:
i32
and:
*i32
when used as function parameters?
- Explain why this function is unsafe:
fn bad() *i32 {
var x: i32 = 0;
return &x;
}
- Write a function that accepts:
[]const u8
and prints the string.
- Write a function that returns an optional integer:
?i32
Return null if division by zero occurs.
-
Organize a small project into modules with clearly separated responsibilities.
-
Write a function
mapthat applies another function to every element of a slice. -
Write a function that computes the average of a slice of floating-point values.
-
Write a module
vector.zigcontaining:
Vec2
add
sub
scale
dot
-
Rewrite a long function into smaller functions with clearer names.
-
Design a public interface for a parser module. Decide which declarations should remain private.
-
Write a function that receives a struct by pointer and modifies one field.
-
Explain why explicit imports help avoid namespace collisions.
-
Write a small command-line calculator using multiple source files.