Given an integer N, it is required to compute the sum of the numbers from 1 to N
ID: 3691149 • Letter: G
Question
Given an integer N, it is required to compute the sum of the numbers from 1 to N. The sum can be computed directly or analytically by the following formula: S= 1+2 + 3+ ... + N (N +1) Let N = 20. Compute the sum by the following 5 methods, using: (1) a for-loop, (2) a conventional while-loop, (3) a forever while-loop, (4) the vectorized sum function, and, (5) the above analytical formula. Write a function, say, fsum.m, that employs a switch structure and evaluates the sum by any of the above 5 methods, with method 5 being the default method. It must have the following usage, where m is the method number, m = 1, 2, 3,4,5: S = fsum(N,m); The sum S grows with increasing N. Using your function fsum and a forever-while loop determine the smallest N such that S > 10^6. Repeat using a conventional while-loop. Do not use the built-in functions sum or cumsum in this problem. Write your code and numerical results for parts (a, b, c) in the space below.Explanation / Answer
Answer:)
Matlab code for B:
function S = fsum(N, m)
n=1;
switch (m)
case 1
for i = 1 : N
S = S + i
case 2
while (n != N)
S=S+n
n=n+1
case 3
while(true)
S=S+n
n=n+1
if(n == N)
S=S+n
case 4
A = 1:N
S = sum(A)
otherwise S = N*(N+1)/2
end
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.