This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2010-02-27 11:41:55

Larry828
Scratcher
Registered: 2007-05-30
Posts: 100+

How do you add up the numbers in a list for a Total?

Say there's a list of only 3 numbers: 2, 4, 8.

How do I write a script to add them up??

And, if numbers keep being added to the list, one by one, how do I keep a running total??

(Why haven't I been able to do this so far??)

Offline

 

#2 2010-02-27 12:08:24

archmage
Scratcher
Registered: 2007-05-18
Posts: 1000+

Re: How do you add up the numbers in a list for a Total?

Try this script

set sum to 0
set i to 0
repeat (length of list){
change i by 1
change sum  by (item (i) of list)
}


Hi, I am Archmage coder extraordinaire. I do Scratch,pascal,java,php,html, AS2 and AS3. Leave me a message if you want coding advice. Also check out my personal website, lots of good stuff about web development, Flash, and Scratch (v1 and v2) !

Offline

 

#3 2010-02-27 13:01:24

Larry828
Scratcher
Registered: 2007-05-30
Posts: 100+

Re: How do you add up the numbers in a list for a Total?

Thanks, archmage!

It works perfectly.

I had all the right components but I just couldn't think it through correctly. And in each case I could see why I was getting the wrong result (the script, unfortunately, was doing *exactly* what I told it to do), but I never could work out the logic.

Thanks again!! 

And it's truly an honor to have one's problem solved by one of the most famous Scratchers of all!!   smile

Offline

 

#4 2010-02-27 13:08:17

archmage
Scratcher
Registered: 2007-05-18
Posts: 1000+

Re: How do you add up the numbers in a list for a Total?

Nah, I am not that great. I learned how to do this sort of stuff in java class.

Heres a tip, its easy to go though things using an i variable.

For example

Code:

//check if touching an enemy 
//Enemies are labled enemy1 to enemy10
set enemies to 10
set i to 0
repeat (enemies){
change i by 1
if touching (join (enemy)(i)){
say(oh no!)
}
}

Don't feel bad abut not working out of logic. For a lot of things in programming you have to learn it from a source because it is too complex to just make up.

Last edited by archmage (2010-02-27 13:10:29)


Hi, I am Archmage coder extraordinaire. I do Scratch,pascal,java,php,html, AS2 and AS3. Leave me a message if you want coding advice. Also check out my personal website, lots of good stuff about web development, Flash, and Scratch (v1 and v2) !

Offline

 

#5 2010-02-27 18:19:24

Larry828
Scratcher
Registered: 2007-05-30
Posts: 100+

Re: How do you add up the numbers in a list for a Total?

Thanks for the tip and extra script to demonstrate how to scan a list.

And thanks for watching the Forums and solving problems for us. Much appreciated!

Offline

 

Board footer