LinkedIn principal author Doug Winnie explains how to loop through values within an array. Using a for loop, you can repeat through all of the elements and stop the loop based on the array’s length function that stores the number of items in the array. The for each loop goes through all of the items in the loop and uses a single variable name to refer to each element without needing to know the array length.
- With a collection of values within an array,…it is common to want to repeat actions using a loop…across all the values within the array collection.…For instance, if I have a collection of values,…I might want to know what is the average of the values…within the array.…To do this, I need to create a loop.…The for loop is a good candidate to iterate…through all of the items in an array…because we have a set number of times we want to repeat.…An array has a function that stores how many values…are within the collection.…
So, for a group like this one,…it knows the array has 12 items.…We can use that as part of our for loop.…I'll start with an iterator.…I'll make sure the iterator is less than the number of items…in the array.…Since we start with zero, the twelfth element index…in the array is 11.…So, 11 is less than 12…which will work for the for loop and then,…when it gets to 12, the loop will end.…Now we can create a new value to store the sum…and then run through the loop.…
With each loop, we will take the specific value identified…
Join Doug Winnie as he explains the principles of programming and helps you connect to core concepts by exploring three ways that programmers perform their jobs. Doug starts by sharing the history of coding and then dives into functions, values, variables, and parameters used to define actions. He covers capturing input from users, creating conditional tests, using loops with arrays, and object-oriented programming basics. He also takes you beyond programming, into processes like debugging, refactoring, and building iteratively.
- Working with values and variables
- Breaking down tasks
- Customizing functions and parameters
- Building conditional tests
- Creating and changing arrays
- Working with objects and classes
- Debugging and refactoring code
- Going beyond the code as a programmer