# Array loop termination in dynamic array

I am practicing loops in arrays, does the dynamic array’s loop can’t be terminated with null character.

```for (int i=0; arr[i]!=''; i++)
```

And how can I terminate these loops without using this format:

```for (const auto& value : arr)
```

## Answer

For an array allocated on the free store

```int* arr = new int[size];
```

there are two ways to know where the end is. The most straightforward is to remember how big it is:

```for (int i = 0; i < size; ++i)
// do something with arr[i]
```

The other way is to set the last element of the array to a sentinel value — a value that won’t show up in the data that you’re working with, so when you see it you know that you’re at the end of the array:

```for (int i = 0; i < size; ++i)
arr[i] = i;
arr[size - 1] = -1;
```

Now you can loop through the array looking at the values:

```for (int i = 0; arr[i] != -1; ++i)
// do something with arr[i]
```

That’s how literal strings work (although they’re not allocated on the free store):

```const char *str = "Hello, world!";
for (int i = 0; str[i] != ''; ++i)
std::cout << str[i];
std::cout << 'n';
```

The tradeoff here is that with the first approach you have to pass an extra parameter around to tell other code how large the array is:

```void do_something(int* arr, int size) {
for (int i = 0; i < size; ++i)
// whatever
}
```

on the other hand, having a sentinel means that you waste the last element:

```void do_something(int* arr) {
for (int i = 0; arr[i] != -1; ++i)
// whatever
}
```

the last element doesn’t have any of the data you’re working with; it’s only there to mark the end.

And, of course, with a sentinel there’s the risk that you haven’t picked a good sentinel value. If you find that value somewhere in the middle of your data the code will stop looping, and won’t process the rest of the data.