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 件のコメント

Stephen23
Stephen23 2016 年 2 月 4 日
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.

サインインしてコメントする。

 採用された回答

Stephen23
Stephen23 2016 年 2 月 4 日
編集済み: Stephen23 2016 年 2 月 4 日

1 投票

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 件のコメント

Jack Kadidlo
Jack Kadidlo 2016 年 2 月 4 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by