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

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일
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

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 Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 2월 4일

댓글:

2016년 2월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by