# Write a for loop that calculates the first 35 numbers of the Fibonacci Sequence.

6 views (last 30 days)
Spaceman on 19 Mar 2024
Answered: Spaceman on 21 Mar 2024
Given : The Fibonacci Sequence is a famous sequence, where the value of each number in the list is the sum of the two before it. The first 5 numbers in the Fibonacci Sequence are 0, 1, 1, 2, and 3. As such, any value in element n of the sequence, is the sum of element n-1 and element n-2.
Find : Create a row vector named fib that contains the sequence of numbers.
Hint: You might want to start your loop at the 3rd element in fib. For the Fibonacci to work, you must know the first 2 digits in the sequence ahead of time.
Issue: I am new to loops, I know there is a way to logically do this. But unfortunately I can't get it to work in the way I have below.
My solution:
% Remember you are filling variable fib
fib=sum(n1+n2)
for n=1:35
if n1<n
n2=n1+1
end
end
Steven Lord on 19 Mar 2024
Can you describe how you'd compute the Fibonacci numbers with pencil and paper? If so, write those steps down in your script file as comments. Then after each of those comments, write down either the code that performs those steps or (if you're not sure how to implement the step) additional comments breaking the step down into smaller pieces that you can implement.
Here's a hint of the first two steps.
% Step 1: Assign the first value in the sequence to the first element of fib
% Step 2: Assign the second value in the sequence to the second element of fib
What's
% Step 3:
Spaceman on 20 Mar 2024
I can understand how to do this on paper, but how to eloquently and succinctly do it with code eludes me, still. I tried making a flow chart for this one.
I know we want N number of elements to be calculated for the sequence. The first 35 starting at the third integer, with the initial 2 needing to be known. N1=1:35; N2= --> We want fib to contain the sequence of numbers. fib=N1+N2 --> Create a loop to do this iteration 35 times (This is where I am stuck).
fib=N1+N2
for N1=1:35
N2=sum(N1)
end
% This makes sense to me, but I am not super comfortable with loops yet.
% Something in my function structure is off, it throws errors.

Spaceman on 21 Mar 2024
Success.
fib=[0 1];
for n=3:35;
fib(n)=fib(n-1)+fib(n-2);
end
fprintf('The first 35 Fibonacci sequence numbers are: ')
The first 35 Fibonacci sequence numbers are:
disp(fib)
Columns 1 through 16 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 Columns 17 through 32 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 Columns 33 through 35 2178309 3524578 5702887

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2023b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!