Write a loop which will sum an array until the sum exceeds an 'n' value?

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

1 Comment

Never call a variable sum, as this in the name of a very important inbuilt function sum. You will break a lot of code by using this variable name. You can check variables names by using the which function.

Sign in to comment.

 Accepted 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.

1 Comment

Got it! Once I figured out how to loop n, the loop worked. Thanks for all your help, as you guessed, I am very new to MATLAB and my professor has not not spent much time going over the basics of the program. Thanks again!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!