Loops and Conditionals
Last updated on 2024-05-28 | Edit this page
Overview
Questions
- What basic loop constructs does Julia offer?
- What is the syntax for conditionals in Julia?
Objectives
- SOME OBJECTIVE
We only cover two basic loop types here: while
and
for
loops, and both are similar to most other programming
languages.
while loops
while
loops in Julia look like this:
For example, the following prints the first few squares:
for loops
for
loops in Julia do look similar to those in
Python:
The equvalent for
loop to the previous example for a
while
loop would look like this:
<iterable>
can be anything that can be iterated
over and <variable>
will, one by one, take values
from that iterable, e.g., an array.
Conditionals
using if
The probalbly most-used syntax for a conditional in programming uses
the if
keyword and Julia does the same. The general syntax
of an if
conditional is as follows:
JULIA
if <condition 1>
<do something>
elseif <condition 2>
<do something else>
else
<do something entirely different>
end
The blocks elseif
and else
are optional,
also as usual.