# Exercises

### Exercises

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:

```zig
std.debug.print("hello, zig\n", .{});
```

to:

```zig
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:

```text
first line
second line
```

#### Exercise 1-3

Declare a constant named `name` and print it.

Expected output:

```text
hello, zig
```

#### Exercise 1-4

Declare two integers and print their sum.

Expected output:

```text
sum = 30
```

#### Exercise 1-5

Write a program that computes the area of a rectangle.

Use:

```text
width = 12
height = 5
```

Expected output:

```text
area = 60
```

#### Exercise 1-6

Write a program that computes:

```text
(10 + 20) * 3
```

Print the result.

#### Exercise 1-7

Write a program that prints command-line arguments.

Run it like this:

```sh
zig run main.zig -- red green blue
```

Expected output:

```text
red
green
blue
```

Ignore the program name.

#### Exercise 1-8

Modify the greeting program so it prints this:

```text
hello, alice and bob
```

#### Exercise 1-9

Write a program that counts newline characters from standard input.

Run it:

```sh
zig run main.zig
```

Type 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:

```text
spaces = 10
tabs = 2
lines = 4
```

#### Exercise 1-11

Write a program that copies standard input to standard output one byte at a time.

Example:

```sh
zig run main.zig
```

Input:

```text
hello
```

Output:

```text
hello
```

#### Exercise 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:

```text
n    square
1    1
2    4
3    9
4    16
5    25
```

#### Exercise 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.

