MATLAB: Write a loop which will sum an array until the sum exceeds an ‘n’ value

loopnested loop

Consider an array x of randomly generated positive and negative integers (given). Write a script that reads the values of x and sums them until the sum value exceeds n. Let n assume the values contained in the following array: n = [20 170 105 57]. Store all the calculated sums (for each n) in a single array A.
This is what I have tried so far, but the script just runs forever and never stops.
The question recommends using nested for loops, but it seems to me that a while loop or 'if else' statement might be more concise.
sum = 0;
c = 0;
n = [20,170,105,57];
for jj = HW1Rand(1,1:20);
while(sum <= n);
c = c + jj;
end
end
c

Best Answer

You increment c inside the while loop, but never check its value. So no matter how many times your code increments the value of c, you never check it and so never stop. Try checking this:
(c <= n);
Note that you also need to loop over the elements of n, because currently your code compare the entire vector of n with one (presumably) scalar value. The behavior of while with a vector input is clearly documented but often confuses beginners. Anyway, you need to resolve the issue by incrementing over n as well.
Also you should never call a variable sum, as this in the name of a very important inbuilt function sum, and you will break a lot of code by redefining this name to be your variable. For the same reason you should never use the names size, length, i, j, cell, etc.