Skip to content

Julia Control Flow

Control flow statements manage the execution order of programs, including conditional statements and loop structures.

Conditional Statements

if-elseif-else

julia
x = 10

if x > 0
    println("Positive")
elseif x < 0
    println("Negative")
else
    println("Zero")
end

# Single-line form
if x > 0 println("Positive") end

if as Expression

julia
x = 10

# if returns value
result = if x > 0
    "Positive"
elseif x < 0
    "Negative"
else
    "Zero"
end

println(result)  # Positive

Ternary Operator

julia
x = 10

result = x > 0 ? "Positive" : "Non-positive"
println(result)  # Positive

# Nested ternary operator
result = x > 0 ? "Positive" : (x < 0 ? "Negative" : "Zero")

Short-Circuit Evaluation

julia
x = 10

# && short-circuit and
x > 0 && println("x is positive")  # Executes
x < 0 && println("x is negative")  # Doesn't execute

# || short-circuit or
x > 0 || println("x is not positive")  # Doesn't execute
x < 0 || println("x is not negative")  # Executes

# Common pattern
function safe_divide(a, b)
    b == 0 && return nothing
    return a / b
end

Loops

for Loop

julia
# Basic for loop
for i in 1:5
    println(i)
end

# Iterate array
arr = ["apple", "banana", "cherry"]
for fruit in arr
    println(fruit)
end

# Iterate string
for c in "Julia"
    println(c)
end

# Iterate with index
for (i, fruit) in enumerate(arr)
    println("$i: $fruit")
end

# Iterate dictionary
dict = Dict("a" => 1, "b" => 2)
for (key, value) in dict
    println("$key => $value")
end

Ranges and Steps

julia
# Standard range
for i in 1:5
    print(i, " ")  # 1 2 3 4 5
end

# With step
for i in 1:2:10
    print(i, " ")  # 1 3 5 7 9
end

# Reverse
for i in 10:-1:1
    print(i, " ")  # 10 9 8 7 6 5 4 3 2 1
end

# Float range
for x in 0:0.5:2
    print(x, " ")  # 0.0 0.5 1.0 1.5 2.0
end

Nested Loops

julia
# Nested for
for i in 1:3
    for j in 1:3
        println("($i, $j)")
    end
end

# Shorthand form
for i in 1:3, j in 1:3
    println("($i, $j)")
end

# Matrix iteration
matrix = [1 2 3; 4 5 6; 7 8 9]
for i in 1:3, j in 1:3
    println("matrix[$i,$j] = $(matrix[i,j])")
end

while Loop

julia
# Basic while
i = 1
while i <= 5
    println(i)
    i += 1
end

# Conditional loop
count = 0
while true
    count += 1
    if count >= 5
        break
    end
end
println("count = $count")

break and continue

julia
# break - exit loop
for i in 1:10
    if i > 5
        break
    end
    println(i)
end
# Output: 1 2 3 4 5

# continue - skip current iteration
for i in 1:10
    if i % 2 == 0
        continue
    end
    println(i)
end
# Output: 1 3 5 7 9

# Labeled break (exit outer loop)
for i in 1:5
    for j in 1:5
        if i * j > 10
            @goto done
        end
        println("$i × $j = $(i*j)")
    end
end
@label done
println("Done")

Comprehensions

Array Comprehensions

julia
# Basic comprehension
squares = [x^2 for x in 1:5]
println(squares)  # [1, 4, 9, 16, 25]

# With condition
evens = [x for x in 1:10 if x % 2 == 0]
println(evens)  # [2, 4, 6, 8, 10]

# Nested comprehension
pairs = [(i, j) for i in 1:3, j in 1:3]
println(pairs)

# Flattened nested
flat = [i * j for i in 1:3 for j in 1:3]
println(flat)  # [1, 2, 3, 2, 4, 6, 3, 6, 9]

# Complex expression
result = [sqrt(x) for x in 1:9 if x % 2 == 1]
println(result)

Generator Expressions

julia
# Generator (lazy evaluation)
gen = (x^2 for x in 1:10)

# Consume generator
for x in gen
    print(x, " ")
end

# Pass generator to function
println(sum(x^2 for x in 1:10))  # 385

# Compare: array comprehension evaluates immediately, generator is lazy

Dictionary and Set Comprehensions

julia
# Dictionary comprehension
squares_dict = Dict(x => x^2 for x in 1:5)
println(squares_dict)

# Set comprehension
unique_remainders = Set(x % 3 for x in 1:10)
println(unique_remainders)  # Set([0, 2, 1])

Exception Handling

try-catch

julia
try
    result = 10 / 0
    println(result)
catch e
    println("Error occurred: $e")
end

# Catch specific types
try
    arr = [1, 2, 3]
    println(arr[10])
catch e
    if e isa BoundsError
        println("Index out of bounds")
    else
        println("Other error: $e")
    end
end

finally

julia
f = nothing
try
    f = open("test.txt", "r")
    content = read(f, String)
catch e
    println("Read error: $e")
finally
    if f !== nothing
        close(f)
    end
end

Throwing Exceptions

julia
function divide(a, b)
    if b == 0
        throw(DivideError())
    end
    return a / b
end

try
    divide(10, 0)
catch e
    println("Caught exception: $e")
end

# Custom error message
function validate_age(age)
    if age < 0
        error("Age cannot be negative")
    end
    if age > 150
        throw(ArgumentError("Age value unreasonable: $age"))
    end
    return true
end

Assertions

julia
# @assert macro
function factorial(n)
    @assert n >= 0 "n must be non-negative"
    n <= 1 && return 1
    return n * factorial(n - 1)
end

# factorial(-1)  # Would throw AssertionError

Scope Rules

Local Scope

julia
# for loop introduces new scope
for i in 1:5
    x = i^2  # x is local variable
end
# x is not accessible here

# let block creates new scope
let
    y = 10
    println(y)
end
# y is not accessible here

Global Scope

julia
x = 10  # Global variable

function modify_global()
    global x  # Declare to modify global variable
    x = 20
end

modify_global()
println(x)  # 20

# Modify global in loop
counter = 0
for i in 1:5
    global counter
    counter += 1
end
println(counter)  # 5

Common Patterns

Conditional Assignment

julia
# Get default value
value = nothing
result = value !== nothing ? value : "default"

# Using something
result = something(nothing, nothing, "default")
println(result)  # "default"

# Using coalesce (similar)
using Missings
result = coalesce(missing, missing, 42)
println(result)  # 42

Early Return

julia
function process(data)
    isempty(data) && return nothing
    
    length(data) < 3 && return "Too short"
    
    # Normal processing
    return sum(data)
end

Accumulation in Loops

julia
# Accumulate using loop
total = 0
for i in 1:10
    total += i
end

# Using reduce
total = reduce(+, 1:10)

# Using sum
total = sum(1:10)

State Machine

julia
function parse_state_machine(input)
    state = :start
    
    for c in input
        if state == :start
            if c == '<'
                state = :tag_open
            end
        elseif state == :tag_open
            if c == '/'
                state = :tag_close
            else
                state = :tag_name
            end
        end
        # ... more state handling
    end
    
    return state
end

Performance Tips

Type Stability

julia
# Bad: type unstable
function unstable(x)
    if x > 0
        return x        # Int
    else
        return 0.0      # Float64
    end
end

# Good: type stable
function stable(x)
    if x > 0
        return float(x)  # Always Float64
    else
        return 0.0
    end
end

Avoid Creating Arrays in Loops

julia
# Bad
result = 0
for i in 1:1000
    result += sum([1, 2, 3])  # Creates new array each time
end

# Good
arr = [1, 2, 3]
result = 0
for i in 1:1000
    result += sum(arr)  # Reuse array
end

Next Steps

After learning control flow, continue with:

Content is for learning and research only.