Help with Homework please Loops are hard
3 views (last 30 days)
Show older comments
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.
WHAT IS THIS I DONT UNDERSTAND LOOPS HELP PLEASE IM BEGGING!!!. x.x
0 Comments
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;
end
However, you have been told to do this with a "while" loop. Therefore, it is equivalent to write:
total = 0;
k=1;
while k <= n
total = total + ((-1)^k * k^2 +5*k)/3^k;
k = k+1;
end
All you have to do is define "n" as required.
2 Comments
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);
More Answers (1)
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
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!