Generating Fibonacci Sequence Using While Loop

Hello all,
I am trying to generate the first Fibonacci Sequence Term greater than 1000 using a while loop. I am using the following code:
fibf(1) = 1;
fibf(2) = 1;
n=3:50;
while fibf(n) < 1000
fibf(n) = fibf(n-1)+fibf(n-2);
end
I am getting the error, 'Index exceeds matrix dimensions'. Any help is appreciated

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 10월 5일

5 개 추천

fibf(1) = 1;
fibf(2) = 1;
n=3
while fibf(n-1) < 1000
fibf(n) = fibf(n-1)+fibf(n-2);
n=n+1;
end

댓글 수: 3

Umesh Pandey
Umesh Pandey 2016년 8월 19일
편집: Umesh Pandey 2016년 8월 19일
fibf(1)=0 ? also it gives one value more than 1000.
To get values exactly less than 1000, you can change the while condition to:
while(fibf(n - 1) + fibf(n - 2) < 1000)
Does the counter variable “n” HAVE to go second in the while loop?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

NEHA THAKUR
NEHA THAKUR 2020년 4월 2일

1 개 추천

fibf(1) = 1;
fibf(2) = 1;
n=3
while fibf(n-1) < 1000
fibf(n) = fibf(n-1)+fibf(n-2);
n=n+1;
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2014년 10월 5일

댓글:

2021년 3월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by