Fibonacci Series using while loop .
Mostrar comentarios más antiguos
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 ? 

Respuesta aceptada
Más respuestas (2)
Mahesh Chilla
el 6 de Jul. de 2023
Editada: Mahesh Chilla
el 6 de Jul. de 2023
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!!
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.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!