Clear Filters
Clear Filters

Help with Homework please Loops are hard

8 views (last 30 days)
Use a while-end loop in a script file to calculate the sum of the first n terms of the series:
Summation sign on the top n bottom k=1 : ((-1)^k * k^2 +5k)/3^k Show the script file and the two results of n = 10 and n = 20.

Accepted Answer

Harry on 1 Nov 2014
So, in the first case, you have to add 10 numbers together. In the second case, you have to add 20 numbers together. I'm sure you know how to add numbers together, so don't be intimidated by the loop.
In my opinion, the natural way to do this sum is with a "for" loop:
total = 0;
for k=1:n
total = total + ((-1)^k * k^2 +5*k)/3^k;
However, you have been told to do this with a "while" loop. Therefore, it is equivalent to write:
total = 0;
while k <= n
total = total + ((-1)^k * k^2 +5*k)/3^k;
k = k+1;
All you have to do is define "n" as required.
Hasan on 1 Nov 2014
So basically all i have to do is say n=1 and n=20 in both cases when i run the code?
Harry on 1 Nov 2014
Edited: Harry on 1 Nov 2014
Yes, you should run it with n = 10 and n = 20.
Note that for large n, the term ((-1)^k * k^2 +5*k)/3^k gets very small. Therefore, the answers for n = 10 and n = 20 will look almost the same. If you type "format long g" before running the code, this will make Matlab display more precision so you can see the difference.
As you use Matlab more, you will find that you don't need to use loops for simple sums like this. Instead, your code will normally run much faster if you operate on vectors. In other words, your loop can simply be replaced with this:
k = 1:n;
total = sum(((-1).^k * k.^2 + 5*k)./3.^k);

Sign in to comment.

More Answers (1)

Ralph Lopez
Ralph Lopez on 9 Mar 2021
Programming Requirements : 1. Implement modularization 2. Two user inputs 𝒙 and 𝒏 3. Provide a re-run (try again) program segment 4. Output must be in tabular form that shows that column for no. of terms, approximate value, and approximate estimate error. 5. Show the number of terms needed to satisfy the criterion.
  1 Comment
Walter Roberson
Walter Roberson on 9 Mar 2021
This does not appear to be an Answer to the question that was asked?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!