The programs in this chapter are small. They are meant to be changed, broken, rebuilt, and studied.
The programs in this chapter are small. They are meant to be changed, broken, rebuilt, and studied.
Do not only read them. Run them.
A programming language is learned by writing programs.
Exercise 1-1
Run the first hello program.
Change the text:
std.debug.print("hello, zig\n", .{});to:
std.debug.print("hello, world\n", .{});Build and run it again.
Exercise 1-2
Print two lines with one call to std.debug.print.
Expected output:
first line
second lineExercise 1-3
Declare a constant named name and print it.
Expected output:
hello, zigExercise 1-4
Declare two integers and print their sum.
Expected output:
sum = 30Exercise 1-5
Write a program that computes the area of a rectangle.
Use:
width = 12
height = 5Expected output:
area = 60Exercise 1-6
Write a program that computes:
(10 + 20) * 3Print the result.
Exercise 1-7
Write a program that prints command-line arguments.
Run it like this:
zig run main.zig -- red green blueExpected output:
red
green
blueIgnore the program name.
Exercise 1-8
Modify the greeting program so it prints this:
hello, alice and bobExercise 1-9
Write a program that counts newline characters from standard input.
Run it:
zig run main.zigType several lines and end the input.
Exercise 1-10
Write a program that counts spaces, tabs, and newline characters.
Print all three totals.
Expected output:
spaces = 10
tabs = 2
lines = 4Exercise 1-11
Write a program that copies standard input to standard output one byte at a time.
Example:
zig run main.zigInput:
helloOutput:
helloExercise 1-12
Break a program on purpose.
Examples:
- remove a semicolon
- misspell
print - use an undeclared variable
- pass the wrong number of arguments
Read the compiler errors carefully.
Exercise 1-13
Write a program that prints a small table.
Expected output:
n square
1 1
2 4
3 9
4 16
5 25Exercise 1-14
Change one program to use var instead of const.
Change the value several times and print the result after each change.
Exercise 1-15
Write a program that prints the integers from 1 to 10.
One number per line.
This chapter introduced:
- source files
- functions
- constants and variables
- arithmetic
- formatted printing
- command-line arguments
- standard input
- loops
- simple error handling
The next chapter examines Zig types and declarations in detail.