Write a loop which will sum an array until the sum exceeds an 'n' value?
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!