Arrays in Julia

In Julia, an array is a collection of elements of a specific type. Arrays are fundamental to Julia and are used extensively in typical Julia code.

# Here we create an array `a` that will hold exactly 5 integers.
# By default, an array is initialized with zeros.
a = zeros(Int, 5)
println("emp: ", a)

# We can set a value at an index using the
# array[index] = value syntax, and get a value with
# array[index].
a[5] = 100
println("set: ", a)
println("get: ", a[5])

# The `length` function returns the length of an array.
println("len: ", length(a))

# Use this syntax to declare and initialize an array
# in one line.
b = [1, 2, 3, 4, 5]
println("dcl: ", b)

# In Julia, you can use the `collect` function with a range
# to create an array of consecutive integers.
b = collect(1:5)
println("dcl: ", b)

# You can use the `fill` function to create an array
# with a specific value repeated.
b = [fill(100, 1); fill(0, 2); 400; 500]
println("idx: ", b)

# Array types are one-dimensional, but you can
# create multi-dimensional arrays using nested arrays.
twoD = zeros(Int, 2, 3)
for i in 1:2, j in 1:3
    twoD[i, j] = i + j - 2
end
println("2d: ", twoD)

# You can create and initialize multi-dimensional
# arrays at once too.
twoD = [
    1 2 3;
    1 2 3
]
println("2d: ", twoD)

Note that arrays appear in the form [v1, v2, v3, ...] when printed with println.

When you run this Julia script, you’ll see output similar to:

emp: [0.0, 0.0, 0.0, 0.0, 0.0]
set: [0.0, 0.0, 0.0, 0.0, 100.0]
get: 100.0
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [0 1 2; 1 2 3]
2d: [1 2 3; 1 2 3]

In Julia, arrays are zero-indexed, meaning the first element is at index 1. Julia also provides powerful array comprehensions and broadcasting capabilities, which are beyond the scope of this basic example but are worth exploring for more advanced array operations.