Repairing a stalled package scan

Mark Yourself Question

  1. Grab a piece of paper and try this problem yourself.
  2. When you're done, check the "I have answered this question" box below.
  3. View the solution and report whether you got it right or wrong.

A MATLAB script scans five recorded package masses in kg. Negative values flag invalid readings. The intended behavior is to consume each visited reading once, add only nonnegative masses, and stop when the accepted total reaches at least 10 kg or all five readings have been consumed.


MATLAB
readings = [-2 4 -1 7 8];   % kg; negative entries are invalid
k = 1;
total = 0;                 % kg
while (k <= 5) && (total < 10)
    if readings(k) < 0
        continue
    end
    total = total + readings(k);
    k = k + 1;
end


Explain why this code does not terminate. Rewrite the loop so that it implements the intended behavior, then determine the final accepted total and the value of k, where k identifies the next unread entry.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Conditional Statements and Loops Questions: