Control Flow in Julia
Learn conditionals, loops, and branching in Julia with practical Docker-ready examples covering if/elseif/else, ternary expressions, for and while loops, and comprehensions
Control flow determines the order in which your program executes statements—which branches it takes and how often it repeats work. Julia provides a familiar set of structured control-flow constructs (if/elseif/else, for, while) that will feel comfortable to anyone coming from Python, MATLAB, or C.
What makes Julia interesting is that, as a multi-paradigm language, control flow is often an expression rather than a statement. An if block returns a value, the ternary operator is idiomatic, and the language leans on iteration over ranges and collections rather than manual index juggling. Combined with comprehensions and broadcasting, Julia lets you write loops that read like mathematical notation while still compiling to fast native code.
In this tutorial you will learn how to branch with conditionals, choose between short-circuit and ternary forms, iterate with for and while loops, control loops with break and continue, and replace explicit loops with comprehensions where appropriate.
Conditionals: if, elseif, else
Julia’s if statement uses the end keyword to close the block—there are no curly braces or significant indentation rules. Note that elseif is a single word.
Create a file named conditionals.jl:
| |
A key difference from C, Python, or JavaScript: Julia conditions must evaluate to a genuine Bool. Writing if 1 raises a TypeError rather than treating the number as truthy. This strictness catches a whole category of bugs.
Ternary and short-circuit expressions
For simple two-way choices, the ternary operator cond ? a : b is idiomatic and concise. Julia also lets you use the short-circuit operators && and || for control flow, not just boolean logic.
Create a file named ternary.jl:
| |
Because && and || return the last evaluated operand, expressions like x > 0 && println(...) only run the right-hand side when needed—a compact, very Julian way to guard a single action.
For loops and ranges
Julia’s for loop iterates over any iterable: ranges, arrays, tuples, strings, dictionaries. Ranges are written with start:stop or start:step:stop and are lazy (they don’t allocate an array).
Create a file named for_loops.jl:
| |
Note Julia’s 1-based indexing: enumerate starts counting at 1, matching the convention used throughout the language and its scientific-computing ecosystem.
While loops, break, and continue
The while loop repeats as long as its condition is true. Use break to exit a loop early and continue to skip to the next iteration.
Create a file named while_loops.jl:
| |
The global keyword inside the while loop deserves attention: in a script’s top-level scope, loop bodies introduce a new local scope, so reassigning the outer countdown requires global. Inside a function this is unnecessary—another reason Julia code is usually organized into functions.
Comprehensions: loops as expressions
Julia’s array comprehensions let you build collections declaratively, often replacing an explicit loop entirely. They support an optional filter condition, mirroring set-builder notation in mathematics.
Create a file named comprehensions.jl:
| |
The generator form sum(x^2 for x in 1:100) is control flow without ever materializing a list—Julia streams the values straight into sum, which is both memory-efficient and fast.
Running with Docker
| |
Expected Output
Running conditionals.jl:
It's mild
Water is above freezing
7 is odd
Running ternary.jl:
Result: pass
x is positive
0 is zero
Running for_loops.jl:
1 2 3 4 5
0 2 4 6 8 10
Fruit: apple
Fruit: banana
Fruit: cherry
1. apple
2. banana
3. cherry
Alice scored 90
Bob scored 85
Running while_loops.jl:
T-minus 3
T-minus 2
T-minus 1
Liftoff!
First square over 50 is 64 (n=8)
1 3 5 7 9
Running comprehensions.jl:
[1, 4, 9, 16, 25]
[6, 12, 18, 24, 30]
[1 2 3; 2 4 6; 3 6 9]
Sum of squares 1..100 = 338350
Key Concepts
- Conditions must be
Bool— Julia rejectsif 1orif "x"; only true booleans are accepted, eliminating truthiness bugs. ifis an expression — branches return values, so you can assign the result of anif/elsedirectly to a variable.elseifis one word and every block (if,for,while,function) is closed withend—no braces, no indentation rules.- Ranges are lazy —
1:2:10describes a sequence without allocating an array, makingfor i in 1:ncheap even for hugen. - Short-circuit operators double as control flow —
cond && actionandcond || actionare idiomatic guards in Julia. - Scope matters at top level — reassigning an outer variable inside a script-level loop needs
global; this disappears inside functions. - Comprehensions and generators replace many loops —
[f(x) for x in xs if cond]andsum(f(x) for x in xs)express iteration declaratively and run fast. - Everything is 1-indexed —
enumerate, ranges, and array access all start at 1, consistent with Julia’s mathematical heritage.
Comments
Loading comments...
Leave a Comment