1.5. Conditionals#
A conditional statement allows a block of code to be executed only if a certain condition is met. To build these statements, we first need to understand how to express logical conditions.
1.5.1. Boolean Expressions#
A boolean expression is an expression that evaluates to either true
or false
. For example, the operator ==
compares two values and returns true
if they are equal and false
otherwise.
123 == 123
true
123 == 124
false
typeof(true)
Bool
1.5.1.1. Relational Operators#
These operators compare two values and produce a boolean result.
Operator |
Description |
---|---|
|
Is |
|
Is |
|
Is |
|
Is |
|
Is |
|
Is |
Note: To type the special Unicode characters like ≠
, ≥
, and ≤
, type their LaTeX command (e.g., \ne
, \ge
, \le
) and press the <Tab>
key.
1.5.1.2. Logical Operators#
These operators are used to combine boolean expressions.
Operator |
Description |
Result |
---|---|---|
|
NOT |
|
|
|
|
|
|
|
x = 10
(x < 20) && (x > 5) # Is x (strictly) between 5 and 20?
true
(x < 20) && (x > 15) # Is x (strictly) between 15 and 20?
false
!(x > 5) # Is it false that x is greater than 5?
false
1.5.2. Chained Comparisons#
Unlike many other languages, Julia allows you to chain comparison operators for a more natural, mathematical syntax. The chained expression is evaluated from left to right as a series of &&
(AND) operations.
# This is equivalent to (1 < 2) && (2 <= 2) && (2 < 3) && ...
1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
true
This syntax makes checking if a variable falls within a certain range incredibly concise and readable.
x = -2.3
# A clean way to check if x is in the closed interval [-3, 4].
# (Type \le or \ge and press Tab for ≤ and ≥).
-3 ≤ x ≤ 4
true
1.5.3. The if
Statement#
An if
statement uses a boolean expression to decide which block of code to execute. The syntax is:
if condition
# Code to run if condition is true
end
If the condition
is true
, the code inside the block is executed. If it’s false
, the code is skipped.
function print_positivity(x)
if x > 0
println("The number is positive.")
end
end
print_positivity (generic function with 1 method)
print_positivity(10)
The number is positive.
# Nothing is printed because the condition x > 0 is false.
print_positivity(-10)
1.5.4. The if-else
Statement#
You can add an else
block to provide an alternative path for when the if
condition is false
.
if condition
# Code to run if condition is true
else
# Code to run if condition is false
end
function print_parity(x)
if x % 2 == 0
println(x, " is even.")
else
println(x, " is odd.")
end
end
print_parity (generic function with 1 method)
print_parity(10)
10 is even.
print_parity(9)
9 is odd.
1.5.5. Chained Conditionals with elseif
#
To handle more than two possibilities, you can chain conditions using elseif
.
if condition1
# Code for condition1
elseif condition2
# Code for condition2
else
# Code if no conditions are met
end
Julia checks the conditions in order. As soon as one is found to be true
, its corresponding code block is executed, and the rest of the chain is skipped.
function compare(x, y)
if x < y
println(x, " is less than ", y)
elseif x > y
println(x, " is greater than ", y)
else
println(x, " is equal to ", y)
end
end
compare (generic function with 1 method)
compare(3, 5)
3 is less than 5
compare(5, 3)
5 is greater than 3
compare(5, 5)
5 is equal to 5
1.5.6. Example: The Fibonacci Sequence#
A common use for if
statements is to handle special cases or initial conditions before starting a more general computation. The Fibonacci sequence is a perfect example.
The sequence is defined by its first two terms, \(F_0 = 0\) and \(F_1 = 1\), and the recurrence relation: $\( F_{k} = F_{k-1} + F_{k-2} \qquad \text{for } k \ge 2 \)$
In our implementation, we’ll first check for the special cases of \(n=0\) and \(n=1\). For any other value of \(n\), we’ll use the recurrence relation.
function fibonacci(n)
# Handle the base cases first.
if n == 0
return 0
elseif n == 1
return 1
end
# General case (n ≥ 2): initialize and iterate.
f_k_minus_2 = 0 # Represents F_{k-2}, starts at F₀
f_k_minus_1 = 1 # Represents F_{k-1}, starts at F₁
f_k = 0 # Will hold the current Fₖ
for k = 2:n
# Calculate the next Fibonacci number.
f_k = f_k_minus_1 + f_k_minus_2
# Update the previous two values for the next iteration.
f_k_minus_2 = f_k_minus_1
f_k_minus_1 = f_k
end
return f_k
end
fibonacci (generic function with 1 method)
fibonacci(10)
55
# The result for n=100 fits within an Int64.
fibonacci(100)
3736710778780434371
# However, n=110 causes an overflow. For larger numbers, you would need
# to modify the function to use BigInt instead of Int64.
fibonacci(110)
-4433243247116178887
1.5.7. Example: Project Euler Problem 1#
Let’s solve the following computational number theory problem using loops and conditionals.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
We need to loop through numbers from 1 to 999 and check if each number is divisible by 3 OR 5. If it is, we add it to a running total.
function solve_euler1(N)
# Initialize the sum
s = 0
# Loop through all numbers from 1 to N-1
for i = 1:(N-1)
# Check if i is a multiple of 3 or 5
if (i % 3 == 0) || (i % 5 == 0)
s += i
end
end
return s
end
solve_euler1 (generic function with 1 method)
First, let’s confirm that our function gives the right answer for the simple example provided in the problem description:
solve_euler1(10) # Should be 23
23
Now we can solve the main problem for numbers below 1000:
solve_euler1(1000)
233168