> For the complete documentation index, see [llms.txt](https://mr-poston-1.gitbook.io/c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mr-poston-1.gitbook.io/c++/2.-going-beyond-the-basics/2.1-vector-basics/2.1.4-looping-through-a-vector.md).

# 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(int i = 0; i < myVector.size(); i++) {...}
```

For-Each Loop:

```
for(type item : myVector) {...}
```

### 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.

```
vector<char> v {'E', 'a', 'g', 'l', 'e'};

for (int i = 0; i < v.size(); i++) {
    cout << i << ": " << v[i] << endl;
}
```

*Output:*

```
0: E
1: a
2: g
3: l
4: e
```

### 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.

```
vector<char> v {'E', 'a', 'g', 'l', 'e'};

for (char letter : v) {
    cout << letter << endl;
} 
```

*Output:*

```
E
a
g
l
e
```

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.

### [Try This Example](https://replit.com/@Poston/214-Looping-Through-a-Vector#main.cpp)
