01-06-2016 11:08 AM
Hi, I was wondering how to get even numbers from a 1D array and find the sum of these even numbers? Any help would be kindly appreciated
01-06-2016 11:12 AM
You can put your array into a for loop, and check if it is even or not (quotient remainder comes to mind). Then you can either create a conditional indexing output tunnel (newer versions) or keep your even number array in a shift register and only add to it if your check is true. After the for loop, you will have an array of the even numbers, which you can put into the Add Array Elements function.
01-06-2016 11:14 AM
Check here for resources:
01-06-2016 11:24 AM
01-06-2016 11:27 AM
Ask one of your classmates, or your teacher, for help.
BS
01-06-2016 12:09 PM
@Gregory wrote:
check if it is even or not (quotient remainder comes to mind).
There is also the trick of ANDing with 1 and seeing if the result is 0. Might be a little more efficient. There's a big long thread somewhere around here about finding odd numbers that I learned that trick from.
01-06-2016 01:29 PM
You should also combine the operations. No need to get an array of all odd numbers first. You can keep a running sum while you are finding them. This wil save you potentially a lot of memory.
There is also a solution that does not even need a loop. try it. 😄
01-06-2016 01:33 PM - edited 01-06-2016 01:37 PM
I wonder what this code does? Yes, it sums the odd numbers if an integer array.
See if you can modify it to sum the even numbers. 😄
01-06-2016 01:36 PM - edited 01-06-2016 01:38 PM
@altenbach wrote:
I wonder what this code does?
(Please try to understand every single element of the code.)
Shouldn't you add 1 to the array before anding it with 1 and then multiply the original array with the AND result?
Ben64
EDIT: OUPS, miss part of your message 😞
01-06-2016 01:43 PM
Yes, if you want the sum of the even numbers, you need to add two more primitives. as I said, it currently sums the odd numbers. 😄 (Code will still be all blue 😉
@ben64 wrote:
Shouldn't you add 1 to the array before anding it with 1 and then multiply the original array with the AND result?
Yes, I added more words later...
If you add one to the array, the resulting sum would be too big, so my tweaks for the even sum are slighly different.