JULIA / CHAPTER 02

Conditions, loops, and local calculations

Beginner

Trace branches and iteration with explicit boolean decisions.

By the end of this chapter

  • Use boolean conditions
  • Trace inclusive ranges
  • Accumulate results inside a function

The idea

Julia if conditions require boolean values; a number is not automatically treated as true or false. Comparisons such as x > 0 create the boolean decisions needed by branches. A for loop can iterate over values directly or over a range. The range 1:4 includes both endpoints, while a stepped range such as 1:2:5 visits one, three, and five. Check the reachable values before counting iterations.

Place reusable loop calculations inside functions so their working variables have a clear local scope. Initialize an accumulator before the loop, update it only when the condition matches, and return it afterward. This structure naturally handles empty input because the loop body runs zero times. break exits the nearest loop, while continue skips to the next iteration without ending the whole loop.

Julia example
function positive_total(values)
    total = 0
    for value in values
        if value > 0
            total += value
        end
    end
    total
end
println(positive_total([4, -2, 3]))
println(positive_total(Int[]))
Result
7
0

The function includes four and three but skips the negative entry. Empty input leaves the initialized accumulator unchanged, giving a defined result of zero.

Try it yourself

Count how many values are divisible by three, treating an empty vector as having zero matches.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this function return?
function total()
    s = 0
    for i in 1:2:5
        s += i
    end
    s
end