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 comentario

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.

Iniciar sesión para comentar.

 Respuesta aceptada

Stephen23
Stephen23 el 4 de Feb. de 2016
Editada: Stephen23 el 4 de Feb. de 2016
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 comentario

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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 4 de Feb. de 2016

Comentada:

el 4 de Feb. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by