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

5. Write a MATLAB script m-file that performs the following: Use a for loop to k

ID: 3754017 • Letter: 5

Question

5. Write a MATLAB script m-file that performs the following: Use a for loop to keep a running sum of the integers between 1 and 25 a. Define a summation variable before the loop that is initially equal to C0 Inside the loop, add the current index to the summation variable (except in the case below) If the current index is 13, skip that iteration of the loop (continue to the next iteration) without adding to the summation If the current summation exceeds 200 (after adding in the current index), print the current index and break out of the loop . After the loop exits, display the final value of the summation b. Use a while loop to implement exactly the same thing as the for loop above. Hint You'll have to define and increment the index manually

Explanation / Answer

solution

MATLAB Code:

(a)

% (a) Using for loop

% Initially set to 0
summation = 0;

% For loop
for index=1:25

% Checking index vvalue 13
if index != 13

% Adding summation
summation = summation + index;

% Checking summation value
if summation > 200
fprintf(" Stopping loop at index %d ", index);
break;
end
end
end

% Printing summation
fprintf(" Summation: %d ", summation);

Sample Run:

Stopping loop at index 21 Summation: 218

____________________________________________________________________________________

(b)

% (a) Using for loop

% Initially set to 0
summation = 0;
index = 1;

% While loop
while index<=25

% Checking index vvalue 13
if index != 13

% Adding summation
summation = summation + index;

% Checking summation value
if summation > 200
fprintf(" Stopping loop at index %d ", index);
break;
end
end

% Incrementing index
index = index + 1;
end

% Printing summation
fprintf(" Summation: %d ", summation);

Sample Run:

stopping loop at index 21

summation :218

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