how do i add up numbers in a list?

Hi, welcome to Snap!.

As it turns out, Snap! provides tools that let you do this sort of computation as a one-liner. But I'm more interested in helping you understand the way you're trying to do it and what's in the way of your solution.

The first thing may sound irrelevant, because the computer doesn't care what you call things. But the names you use can really confuse you. In particular, you used the name NUMBER for a list of numbers. My guess is that if you'd called it NUMBERS you would then not have written INDEX+NUMBERS to try to add INDEX, which is a single number, to... what? To all the numbers?

(I'm guessing that English isn't your native language, because you used PRODUCT for the name of the result you're trying to accumulate. "Product" does mean "the result of a process," as in the product of a factory, but it also means the result of a multiplication, as in "the product of 2 and 3 is 6." So it's a confusing name, too, but it's not the most problematic one. It didn't mislead you the way NUMBER did. The idiomatic name for a variable in which you are accumulating the result of a computation is RESULT, but in this example people use SUM, too.)

So what you need inside the loop is

SET (PRODUCT) TO (result-so-far) + (one-new-number)

You tried to do the one-new-number part with the first SET PRODUCT... inside the loop, but that eliminates the value you'd already accumulated in earlier repetitions.

You also have an off-by-one error in keeping track of INDEX.

I hope this helps. Feel free to ask further questions if not.

Click the arrow for the one-line solution if you don't want to work it out yourself.

Also, one of the points of custom blocks, of writing your own procedures, is that you can generalize the result, instead of building a particular set of numbers into the procedure. The way to do that is, in the Block Editor, to click on the plus sign to the right of the name SUM in the hat block at the top. Then you can give a name to the list of numbers, such as NUMBERS. Then you don't SET that name inside the block. Instead, when you call the block, there will be a list input slot and you can drag the list you want to use into that input slot.

And if, in the initial Make a Block dialog box, you select Reporter (oval) shape instead of Command, you can put the result in a REPORT block so that it can be used as part of a larger computation. (For example, if you wanted the average of the list items, you'd find their sum and then divide by the number of items.)

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.