Fibonacci sequence with loop
조회 수: 43 (최근 30일)
이전 댓글 표시
I need help with these exercise:
Write a function Fibonacci(n) that takes n as an
input and produces the corresponding Fn as an output
• Use a for loop that computes the first 10 numbers (1<= n <= 10)
• Use a while loop that computes all Fibonacci numbers below 1000 (All n that Fn<1000).
If you can also add explanations it will be perfect
댓글 수: 2
James Tursa
2020년 5월 1일
What have you done so far? What specific problems are you having with your code?
채택된 답변
Prasad Reddy
2020년 5월 1일
clc
clear all
Fibonacci(1000)
function fibn=Fibonacci(n)
fibn=[1 1];
i=3;
while fibn(i-1)<n
fibn(i)=fibn(i-2)+fibn(i-1);
i=i+1;
end
fibn=fibn(1:end-1);
end
% This is code in While loop. please try to understand it. if dont understand please leave a comment.
% Please give a up thumb if this code works. thank you in advance.
추가 답변 (2개)
Prasad Reddy
2020년 5월 1일
clc
clear all
Fibonacci(10)
function fibn=Fibonacci(n) % we are defining a function Fibonacci
fibn=[1 1] % initialiing first two values for fibonacci series
for i=3:n % since already two values are present we are starting the loop from third element
fibn(i)=fibn(i-2)+fibn(i-1); % i th element in fibnochi series is the sum of previous two elements
end
end
댓글 수: 8
Prasad Reddy
2020년 5월 1일
편집: Prasad Reddy
2020년 5월 1일
@ Lisa Fontana Ok madam i can understand. post any questions which you dont understand, we are ready to help. It seams that this is your firt question in this community. happy learning.
Tanuj Monu
2022년 1월 23일
function f = fib(n)
f(1) = 1;
f(2) = 1;
for i = 3:n
f(i) = f(i-1) + f(i-2);
end
f = f(end);
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!