Fibonacci Series using while loop .
48 次查看(过去 30 天)
显示 更早的评论
This is the code I have written for the generation of Fibonnaci series for n < 200 using while loop .
%% Fibonacci series using while loop %%
n=200 ;
fibo = [1,1] ;
i = 3 ;
while i < n
fibo(i) = fibo(i-1)+fibo(i-2);
i=i+1 ;
end
But it gives me 0 for all values and gives garbage values for last few elements . What could be possible reason for this ?
2 个评论
Torsten
2023-7-6
But it gives me 0 for all values and gives garbage values for last few elements . What could be possible reason for this ?
The reason is that n is too large.
采纳的回答
Aditya Singh
2023-7-6
编辑:Aditya Singh
2023-7-6
Hi,
I understand you are getting garbage values. The issue in your code is that you have not initialized the fibo array with enough elements to store the Fibonacci series up to n. As a result, when you try to access elements beyond the initial two elements, you encounter garbage values. The following code works fine.
n = 200;
fibo = zeros(1, n); % Initialize the fibo array with zeros
fibo(1) = 1;
fibo(2) = 1;
i = 3;
while i <= n
fibo(i) = fibo(i-1) + fibo(i-2);
i = i + 1;
end
% Display the Fibonacci series
disp(fibo);
Also, just an additional information, keep in mind the range of integer or data type you are using. After a certain time, they would overflow and give you garbage values.
Hope it helps!
0 个评论
更多回答(2 个)
Mahesh Chilla
2023-7-6
编辑:Mahesh Chilla
2023-7-6
Hi Siddhesh!
To generate Fibonacci series for n < 200 using while loop, your code is correct, you might have missed noticing the mulitplying factor in the output that is 1.0e+41.
%% Fibonacci series using while loop %%
n=200 ;
fibo = [1,1] ;
i = 3 ;
while i < n
fibo(i) = fibo(i-1)+fibo(i-2);
i=i+1 ;
end
disp(fibo);
You can also use the other method suggested by Aditya, which gives the same output as your method.
The following code verifies both methods
n = 200;
fib = [1, 1];
i = 3;
while i < n
fib(i) = fib(i-1) + fib(i-2);
i = i + 1;
end
% The resulting Fibonacci sequence is stored in the 'fib' array
n = 199; %changing n to 199, because the 'fib' array is of size 199
fibo = zeros(1, 199); % Initialize the 'fibo' array with zeros
fibo(1) = 1;
fibo(2) = 1;
i = 3;
while i <= n
fibo(i) = fibo(i-1) + fibo(i-2);
i = i + 1;
end
% The resulting Fibonacci sequence is stored in the 'fibo' array
% To check if 'fib' and 'fibo' are the same.
isequal(fib,fibo)
Hope this helps,
Thank you!!
0 个评论
Yash
2024-1-30
I made this code by myself only and found it correct for every possible value :
N = 200;
a = zeros(1,N);
a(1) = 1;
a(2) = 2;
count = 3;
while (count<=N)
a(count) = a(count-1)+a(count-2);
count = count + 1;
end
disp(a(N));
I hope this code is helpful for everyone.
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!