Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This question is written in MATLAB Given an integer N, it is required to compute

ID: 3693823 • Letter: T

Question

This question is written in MATLAB

Given an integer N, it is required to compute the sum of the numbers from I to N. The sum can be computed directly or analytically by the following formula: S = 1+2+3+ +N = 1/2 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

(a) The answer is 210.

1)

n=20;

sum1=0;

for i = 1:n
sum1 += i;
end

disp(sum1);

2)

n=20;

sum1=0;

while(i<=n)
sum1 += i;
i+=1;
end

disp(sum1);

3)

n=20;

sum1=0;

while 1
sum1 += i;
i+=1;
if(i>n)
break
end
end

disp(sum1);

4)

n=20;

arr = 1:n;
sum1 = sum(arr);   

disp(sum1);

5)

n=20

sum1 = (n*(n+1))/2;

disp(sum1);

(b)

function sum1 = fsum(n,m)
sum1 =0;
switch(m)
case 1
for i = 1:n
sum1 += i;
end
case 2
i=0;
while(i<=n)
sum1 += i;
i+=1;
end
case 3
i=0;
while 1
sum1 += i;
i+=1;
if(i>n)
break
end
end
case 4
arr = 1:n;
sum1 = sum(arr);
case 5
sum1 = (n*(n+1))/2;
otherwise
sum1 = (n*(n+1))/2;
end
end
disp(fsum(100,1));
disp(fsum(100,2));
disp(fsum(100,3));
disp(fsum(100,4));
disp(fsum(100,5));
disp(fsum(100,6));

(c) The answer is 1414

Forever while loop:

st = 1;
while 1
if(fsum(st,5)>1000000)
break;
end
st+=1;
end
disp(st);

traditional while loop:

st = 1;
while(fsum(st,5)<1000000)
st+=1;
end
disp(st);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote