Learning C++: Part 2: Arrays

Learning C++


Arrays

In programming terminology, an array is a sequence of values. In C++, and in many other programming languages as well, they can be accessed through their index, the position of the entry relative to the first in the series.

As mentioned in the previous part, all variables have types in C++. This also goes for arrays. They are defined like other variables in part, but with opening and closing square brackets at the end. The number in the middle of the square brackets is its length.

The length of an array is its total number of entries. This tells C++ that there will only ever be that many entries. Trying to access an index more than the total will result in an error.

Indices

In C++, the first position in an array is 0. Every entry after the first has a position of one more than the last. This means that an array of six entries will have indices starting with zero up to five. (This is often expressed as the length minus one.)

Once an array has been defined, its entries can be accessed through their position. Using the name of the variable containing the array, an opening square bracket, the index, and a closing square bracket, its value can be obtained.

Character Arrays

Many programming languages that came after C++ introduced a concept called a string. In programming terminology, a string is a sequence of letters, numbers, or other, special characters. In C++, this can be represented as an array of characters without a fixed length.

Instead of using single quotes for each, character arrays use double-quotation marks to mark the beginning and ending of the entries. While defined slightly differently, character arrays otherwise act like other types of arrays.

Note: There is, technically, a string type in C++. However, as it operates similarly to more complex data types, it will be covered in that later section.

Multidimensionality

Arrays can contain other arrays. This changes it from having a single dimension to be multi-dimensional. Like other single-dimensional arrays, they are defined through including the length of each dimension within the array.

To access an index of an array within an array, it is referenced through additional opening and closing square brackets with the index of each entry listed.

Play with the example on Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.