Fibonacci Series using while loop .
52 ビュー (過去 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!