# For Loop to Sum numbers in a list

I'm asked to create a For[] loop that will sum positive numbers in a list. I am unsure of how to do this.

For[i = 0, i <= Length[List], i += 1, result += i];


result

This is what i have so far where List is the list of numbers and result is the summation of all the positive numbers. I am aware this is not right though.

• Just to get it out of the way: see this and this. Apart from class exercises, you shouldn't need to use For[]. – J. M.'s technical difficulties May 16 at 9:05
• do you have example of such a list that you want to sum? – Nasser May 16 at 9:17
• Better use Total@*Ramp... It is vectorized and thus much more efficient thatn top-level loops. – Henrik Schumacher May 16 at 9:33
• A variation of @Henrik's proposal is list.Unitize[Ramp[list]]. – J. M.'s technical difficulties May 16 at 11:24
• and so list.UnitStep@list – Chris Degnen May 16 at 13:08

bill = {3, -5, 2, -12, -4, -1, -8, 10};
Total[Select[bill, # > 0 &]]


An even shorter way, from this question, is

Total[Select[bill, Positive]]


The answer is 15. I believe that covers the OP's request, but it might be something more complicated. On documentation,

https://reference.wolfram.com/language/ref/Select.html

List={3, -5, 2, -12, -4, -1, -8, 10}

There are many ways to do this in Mathematica, without using For.

One way could be to first filter out the positive numbers, then call Total

list = {3, -5, 2, -12, -4, -1, -8, 10};
positiveNumbersOnly = Cases[list, x_ /; Positive[x] -> x]

(*{3, 2, 10}*)

Total[positiveNumbersOnly]

(* 15*)


You can combine the above into one call

 Total@Cases[list, x_ /; Positive[x] -> x]


I am sure one can come up with 10 other ways to do this if needed.

For example

 Total[If[# > 0, #, 0] & /@ list]
(* 15 *)


Another is

 Total[Clip[list, {0, Infinity}]]
(* 15 *)

• If using Cases[], you could just do Cases[list, x_?Positive]. – J. M.'s technical difficulties May 16 at 11:22

It's just for fun.

{3, -5, 2, -12, -4, -1, -8, 10} //. {b_, c_, a___} :> {Ramp[b] + Ramp[c], a}//First