Do not understand why my code isn't working!

2 views (last 30 days)
Matt
Matt on 29 Mar 2011
The problem I am assigned says, ) Use a while loop to determine how many terms in the series 2k, k = 1, 2, 3, …, are required for the sum of the terms to exceed 1500. The program should print the count of the minimum number of terms needed to exceed 1500 using fprintf. Make sure the output tells the person looking at it what the number represents.
What I did was use a for loop to create a vector from 2^1 up to 2^11. (Because 2^11 > 1500) I then used a while loop to add each element in the vector up. This is my code. (This is not the completed assignment, I still need to do the displays and stuff, but I wanted to get the core structure done first.)
s=[1];
for i=1:11
s(i+1)=2^i;
end
summ=0;
k=1;
terms=0;
while k<=12
while summ<=1500
summ=summ+s(k);
terms=terms+1;
k=k+1;
end
end
When I run the program, it does nothing. I then press CTRL+C and see that "terms" and "sum" are correct. (I would have to subtract 1 from the terms because it is one term over 10.) Help!

Answers (1)

Andrew Newell
Andrew Newell on 29 Mar 2011
The reason that is does nothing is that you are stuck in an infinite loop. The inner loop ( while summ<=1500 ) runs until k=12, then exits to the outer loop. Then you get this sequence happening over and over:
while k<=12 % true (k=12)
while summ<=1500 % false (skip to end)
...
end
end % k=12 because the inner loop was skipped
You don't really need the outer loop - you're aiming for a finite sum, so the inner loop will definitely terminate.
Another thing to think about: the terms in s are 1,2,4,8,16, ... Is that what the question asks for?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!