While Loop Question (Ungraded)
1 view (last 30 days)
F = [1,1]
evensum = zeros(1,4000000);
while F < 4000000
if F == 1
evensum(1,F) = F;
evensum = evensum(1,F-1) + evensum(1,F-2);
F = F+1
The question is:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 1, the first 10 terms will be: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
• Your task is to consider the terms in the Fibonacci sequence whose values do not exceed four million, and find the sum of the even-valued terms.
• Use a while loop.
• Create a vector F, whose first two elements are 1 and 1, and each additional element is calculated in the while loop using the Fibonacci sequence.
• Again use the rem function to determine if a number is even.
Name your variable for the sum of the even-valued terms evensum
I am unable to avieve this. Does anybody know where I went wrong and can help? This is an ungraded question.
Yasasvi Harish Kumar on 13 Feb 2019
You have started with F as an array but use it in the while loop and if condition as a variable.
The solution to your problem can be achieved by assigning the array F with indicies.
The following code should be able to solve your problem.
F = [1,1];
evensum = 0;
i = 2;
while F(i) < 4000000
i = i+1;
F(i) = F(i-1) + F(i-2);
if rem(F(i),2) ==0
evensum = evensum + F(i);