All lessons

Loops

8 min · OCaml

Repeat work without writing it out a hundred times.

OCaml · Loops0/5 cleared

Enemy 1 of 5

for loops and Printf.printf

Writing the same instruction a dozen times by hand doesn't scale — if you needed to print every number from 1 to 1000, you'd want a way to describe "do this once per number" and let the language handle the repetition. OCaml's `for` loop does exactly that over a range of integers.

`for i = start to finish do ... done` counts from `start` to `finish`, **inclusive of both ends**, binding each value to `i` in turn. This is a genuine difference from many other languages' `for`/range constructs that exclude the upper bound — in OCaml, `for i = 0 to 2 do ... done` runs for `i = 0`, `1`, and `2`, three iterations total, both endpoints included. Keep this in mind, since assuming the upper bound is excluded (as it often is elsewhere) is an easy off-by-one mistake to make here.

`Printf.printf` is OCaml's formatted-printing function, modeled closely on C's `printf`: `"%d\n"` is a format string where `%d` is a placeholder for an integer argument and `\n` is an explicit newline character. `Printf.printf "%d\n" i` substitutes `i` into the `%d` slot and prints the result. This is a different, more general tool than `print_int`/`print_endline`, useful once you need to interleave multiple values and literal text in one line.

You
Invisible Heisenbug
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.

Stuck? Ask Rena

Your AI tutor that gives assistance.

Asking Rena in lessons is on Ultimate.