If Else in Julia

Branching with if and else in Julia is straightforward.

# Here's a basic example.
if 7 % 2 == 0
    println("7 is even")
else
    println("7 is odd")
end

# You can have an `if` statement without an else.
if 8 % 4 == 0
    println("8 is divisible by 4")
end

# Logical operators like `&&` and `||` are often useful in conditions.
if 8 % 2 == 0 || 7 % 2 == 0
    println("either 8 or 7 are even")
end

# A statement can precede conditionals; any variables
# declared in this statement are available in the current
# and all subsequent branches.
if (num = 9; num < 0)
    println("$num is negative")
elseif num < 10
    println("$num has 1 digit")
else
    println("$num has multiple digits")
end

Note that you don’t need parentheses around conditions in Julia, but the end keyword is required to close each block.

To run this Julia code, save it in a file (e.g., if_else.jl) and execute it using the Julia interpreter:

$ julia if_else.jl
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Julia supports the ternary operator, which provides a concise way to write simple if-else statements:

result = condition ? value_if_true : value_if_false

This can be useful for simple conditional assignments.