liveBook · Manning

Loop

As explained in Julia as a Second Language

A loop is a programming construct that repeatedly executes code while a specified condition remains true or until a termination condition is met.

A loop runs the same code repeatedly, making it useful when a calculation must be performed for many inputs. A trigonometric table, for instance, needs a value at each angle rather than a separate handwritten calculation for every row. section 3.1

A `while` loop repeats its body while a Boolean condition is true. In `i = 0; while i < 5; i += 1; println(i); end`, updating `i` eventually makes the condition false. The loop does not display its own result in the REPL: a `while` expression evaluates to `nothing`. Use `print` or `println` when you want to see values produced along the way. section 3.3

When the values to visit are known, a `for` loop removes the manual counter update. `for i in 0:4; println(i); end` prints 0 through 4. The range `0:15:90` visits angles from 0 through 90 in steps of 15. A range is an iterable: an object a `for` loop can visit one value at a time. section 3.3.4

Repeated calculations can take several forms:

  • Build a factorial with `while`: start a product at 1, multiply by `n`, and decrease `n` until it falls below 1. section 3.5
  • Calculate a Fibonacci number with `for i in 2:n`, updating the previous and current values on each pass. This replaces recursive calls with explicit bookkeeping. section 3.10.2

Iteration and recursion can solve the same problem. Recursion may be simpler to write, while iteration often performs better; choose according to the clarity and performance the task needs. Beyond ranges, Julia collections can support `for` loops by providing iteration methods. section 3.10.2 section 12.8

How Julia as a Second Language covers it

How deep it goes
Works through while conditions and stepped for-loop ranges, then identifies collection iteration methods without implementing them here.
Examples
Demonstrates printed ranges, stepped angles, iterative factorial, and Fibonacci calculations.
What it assumes
Introduces Boolean conditions before loops and starts with simple assignments and REPL examples.
What you can do after
Build it from scratch: write condition-controlled and range-based loops that update state and terminate.
How it connects
Connects loops to Boolean expressions, ranges, iterable collections, and recursion.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.