Arrays

It would get very tedious to make 300 variables of the same kind. num1, num2, num3, num4, and so on. This is what arrays can be used for.

What is an array?

If a variable is like a box, then an array is like a bunch of boxes on a shelf.

int numbers[ 300 ];

This is how you declare an array. There's only one main difference between this, and declaring a normal array: the [ 300 ] part.

The brackets ([]) are what you use when declaring an array, and inside you put the capacity. Here, we have 300 integers in an array.

How do you use it?

Accessing an array is simple:

numbers[ 7 ] = 92;

As you can see, accessing an array is almost the same as using any other variable. We just use the brackets again, and put the index of the element we want inside it. Then, we use it like any other variable. The brackets you use for accessing an index is called the subscript operator.

One thing that could become confusing is that array indices start at 0, not 1. This means that, for an array with three elements, you have the indices 0, 1, and 2:

int moreNumbers[ 3 ];
moreNumbers[ 0 ] = 68;
moreNumbers[ 1 ] = 37;
moreNumbers[ 2 ] = 76;

Trying to access an element past the last one is undefined behavior, usually a segmentation fault.

Initializing an array

It would get annoying to have to initialize each variable one by one. There are a couple different ways to do this:

int evenMoreNumbers[ 5 ] = { 4, 7, 21, 78, 12 };

Keeping the exact number of elements in sync with the number in the declaration might be a pain, though. So you can omit the number when initializing it this way!

int severalNumbers[] = { 23, 5, 23, 65, 12, 76, 34, 98, 123, 67, 12, 76 };

Conclusion

Wow, that lesson went by fast! We'll learn about something that lets you make resizable arrays later, but for now, you get to learn about conditional statements. :)

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 3.0 License