MATLAB Answers

For loop for fibonacci series

732 views (last 30 days)
Yixiang Guice
Yixiang Guice on 18 Nov 2018
Answered: Syeda Atiya on 24 Jan 2020 at 6:51
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
Yixiang Guice on 18 Nov 2018
I can include the equation given for this question if required

Sign in to comment.

Accepted Answer

Aquatris
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

  2 Comments

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

Sign in to comment.

More Answers (1)

Syeda Atiya
Syeda Atiya on 24 Jan 2020 at 6:51
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

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags