# For loop for fibonacci series

1,516 views (last 30 days)
Yixiang Guice on 18 Nov 2018
Answered: Syeda Atiya on 24 Jan 2020
i am supposed to write a fibonacci series that calculate up to n term and (n-1) term but i am stuck at calculating the (n-1)term. can anyone help? ( i am new to matlab)
a = 0;
b = 1;
x = n-1;
n = input('Enter number of term desired');
for i = 1:n %term for n
fprintf('\t')
fprintf('%d',a);
c = a + b;
a = b;
b = c;
end
for i = n:x %term for n-1
fprintf('\t')
fprintf('%d',a);
c = a + b;
a = b;
b = c;
end

#### 1 Comment

Yixiang Guice on 18 Nov 2018
I can include the equation given for this question if required

Aquatris on 18 Nov 2018
Edited: Aquatris on 18 Nov 2018
In case of series, it is better to store each value. Please see below code that generatesa fibonacci sequence, and stores all the values in the variable"a";
a(1) = 0;
a(2) = 1;
n = input('Enter number of term desired ');
for i = 3:n
a(i) = a(i-1)+a(i-2);
end
From here, if you want the n'th term, you do a(n), if you want the n-1, then you do a(n-1).
You method of trying to find the n-1 term can work with the following modification;
a = 0;
b = 1;
n = input('Enter number of term desired');
for i = 1:n-2 %term for n
c = a + b;
a = b;
b = c;
end
a_n = c; % nth term
a_n1 = a; %(n-1) term

Yixiang Guice on 18 Nov 2018
may i ask why is the i from 3 : n instead of 1 to n?
Aquatris on 18 Nov 2018
Because the first two terms of your fibonacci series are (0) and (1) already.

Syeda Atiya on 24 Jan 2020
a = 0;
b = 1;
n = input('Enter number of term desired');
for i = 1:n-2 %term for n
c = a + b;
a = b;
b = c;
end
a_n = c; % nth term
a_n1 = a; %(n-1) term