MATLAB: Convert the while loop into for loop without using the if statement

for loop

This is the original code
series=1; k=2; exact= pi^2/6;
while abs((series-exact)/exact)>=1e-4
series=series+1/k^2;
k=k+1;
end
disp(['number of terms = ' int2str(k-1)])

Best Answer

Although this seems like a homework question, however, you have shown some effort, so I will explain it a bit.
The original code uses a while loop to iterate over odd numbers and sum their values. Using for loop, you don't need to increment the counter manually. For loop will automatically increment the counter with specified step-size. For example,
for counter = 1:2:value-1
% increment total
end
Remember, in this case, you don't need to increment the counter variable or check the if condition rem(counter,2) == 1 inside the for loop. You just need to increment the total variable.
Related Question