<!-- Control flow · Tin · https://tin.ad/docs/learn/control/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 4 of 34

# Control flow

**Goal.** Choose and repeat with `if`, `while` and `for`, and use blocks as values.

## Choosing with if

`if` runs a block when a condition is true. `else if` and `else` handle
the other cases. The condition needs no parentheses, but the braces are always required.

*if.tin · tin run if.tin*

```tin
fn main() {
  let temperature = 31
  if temperature > 30 {
    print("hot")
  } else if temperature > 15 {
    print("mild")
  } else {
    print("cold")
  }
}
```

<!-- output -->
```text
hot
```

## if has a value

With an `else`, an `if` is an expression: it produces the value of whichever branch ran.
That replaces the `?:` operator from other languages, and it works inside strings too.

*if-value.tin · tin run if-value.tin*

```tin
fn main() {
  let stock = 0
  // with an else, if is an expression: it has a value
  let label = if stock == 0 { "sold out" } else { "{stock} left" }
  print(label)
  print("We have {if stock > 0 { "some" } else { "none" }}.")
}
```

<!-- output -->
```text
sold out
We have none.
```

A condition must be a `bool`. There are no "truthy" values: a number or a string is never true
on its own. Say what you mean, such as `items > 0`:

*no-truthy.tin · tin check no-truthy.tin*

```tin
fn main() {
  let items = 3
  if items {
    print("not empty")
  }
}
```

<!-- compiler output -->
```text
error: expected bool, found int
 --> no-truthy.tin:3:6
  |
3 |   if items {
  |      ^^^^^
```

## Repeating with while

`while` repeats its block as long as the condition holds.

*while.tin · tin run while.tin*

```tin
fn main() {
  var n = 1
  while n < 100 {
    n = n * 2
  }
  print("first power of two from 100: {n}")
}
```

<!-- output -->
```text
first power of two from 100: 128
```

## Counting with for

`for i in a..b` counts from `a` up to, but not including, `b`. So
`0..3` is 0, 1, 2, and `1..101` is 1 to 100.

*for-range.tin · tin run for-range.tin*

```tin
fn main() {
  for i in 0..3 {               // 0, 1 and 2: the end is not included
    print("lap {i}")
  }
  var total = 0
  for n in 1..101 {
    total += n
  }
  print("1 + 2 + ... + 100 = {total}")
}
```

<!-- output -->
```text
lap 0
lap 1
lap 2
1 + 2 + ... + 100 = 5050
```

`for` also walks the items of a list. Add a second name to get each item's position too.
(Lists get their own chapter later. For now, `[…]` is a list.)

*for-items.tin · tin run for-items.tin*

```tin
fn main() {
  for word in ["red", "green", "blue"] {
    print(word.upper())
  }
  for i, word in ["red", "green", "blue"] {   // with the position, from 0
    print("{i}: {word}")
  }
}
```

<!-- output -->
```text
RED
GREEN
BLUE
0: red
1: green
2: blue
```

## Skipping and stopping

`continue` jumps to the next round of the loop. `break` leaves the loop.

*break-continue.tin · tin run break-continue.tin*

```tin
fn main() {
  for n in 1..20 {
    if n % 3 != 0 { continue }   // skip to the next n
    if n > 10 { break }          // leave the loop
    print(n)
  }
}
```

<!-- output -->
```text
3
6
9
```

`loop` repeats forever, until a `break` or `return`. Use it when the stopping
point is easiest to decide in the middle of the work.

*loop.tin · tin run loop.tin*

```tin
fn main() {
  // loop runs until a break (or a return)
  var guess = 1.0
  var steps = 0
  loop {
    guess = (guess + 2.0 / guess) / 2.0   // Newton's method for the square root of 2
    steps += 1
    if steps == 5 { break }
  }
  print("sqrt(2) is about {guess.fixed(6)} after {steps} steps")
}
```

<!-- output -->
```text
sqrt(2) is about 1.414214 after 5 steps
```

## Blocks are expressions

This is the rule from the last chapter, applied everywhere. Any `{ … }` block has a value: its
last line. Names you make inside it don't leak out.

*block-value.tin · tin run block-value.tin*

```tin
fn main() {
  // a block { } is an expression too: its value is its last line
  let area = {
    let width = 3
    let height = 4
    width * height
  }
  print(area)
}
```

<!-- output -->
```text
12
```

## Tasks

### Task 1: FizzBuzz

Print the numbers 1 to 15, but print `Fizz` for multiples of 3, `Buzz` for multiples of
5 and `FizzBuzz` for multiples of both. Try to use one `print` and an `if`
expression.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
fn main() {
  for n in 1..16 {
    let line = if n % 15 == 0 { "FizzBuzz" }
    else if n % 3 == 0 { "Fizz" }
    else if n % 5 == 0 { "Buzz" }
    else { "{n}" }
    print(line)
  }
}
```

<!-- output -->
```text
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
```

### Task 2: Sum of digits

Write `digitSum(number: int): int` that adds the digits of a number: `2026` gives
`10`. Hint: `n % 10` is the last digit and `n / 10` drops it.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```tin
fn digitSum(number: int): int {
  var n = number
  var sum = 0
  while n > 0 {
    sum += n % 10
    n = n / 10
  }
  sum
}

fn main() {
  print(digitSum(2026))
  print(digitSum(99999))
}
```

<!-- output -->
```text
10
45
```

### Task 3: A staircase

Print four lines: `*`, `**`, `***` and `****`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```tin
fn main() {
  for row in 1..5 {
    print("*".repeat(row))
  }
}
```

<!-- output -->
```text
*
**
***
****
```

## Recap

- `if` has a value, so it replaces the ternary.
- `for i in 0..n` counts; `break` and `continue` work as usual.
- A block's last expression is its value.

In the reference: [Control flow](https://tin.ad/docs/ref/language/#control)
