2.1.4 Looping Through a Vector
You can loop through a vector similar to how you loop through lists in other languages. The two most common methods are for loops and for-each loops.
For Loop:
For-Each Loop:
For Loop
Vectors have a size function that allows us to loop over the entire vector. Size returns the number of values, so the indices will go from 0 to size - 1. Inside the loop, you access each element by its index.
Output:
For-Each Loop
For-each loops allow us to access each element in order, but we do not have a counter variable to use as reference. Notice the name is for-each, but the loop still only uses the for keyword.
Output:
In this loop, the variable letter takes on a new value each time through the loop. The first time it is an E
, then takes the a
next time through and continues until the end.
Last updated