sbac
sbac

Reputation: 2081

How to initialize an array in Julia when you don't know their dimensions in first place

I am trying to compute the Fibonacci sequence until a term less than 4*10^6. How can I define the dimensions of the f array when I don't know at first when to stop? In this case, I defined by trial and error f = [1:32;].

k = 32
f = [1:k;]
for i in 1:k
    if i < 3
        f[i] = i
    elseif f[i] < 4*10^6
        f[i] = f[i-1] + f[i-2]
    else
        break
    end
end

Upvotes: 2

Views: 64

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69829

You do not have to define it upfront.

Just use push!:

f = [1, 2]
while true
    fi = f[end] + f[end-1]
    fi < 4*10^6 ? push!(f, fi) : break
end

Side note: in case of Fibonacci sequence it is relatively easy to calculate k using the formula given in Wikipedia in Computation by rounding section. Also normally you define f[2] to be equal to 1 and not to 2 as in your question.

Upvotes: 2

Related Questions