Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,326 Categories: 12

Total Tutorial Views: 41,403,492

C++ Beginners Tutorial: Arrays.

Tutorial Name: C++ Beginners Tutorial: Arrays.  

Category: PC Tutorials

Submitted By: Nissan

Date Added:

Comments: 0

Views: 2,185

Related Forum: PC Building Forum

Share:

C++ Beginners Tutorial: Arrays.


Arrays are basically a list of variables, grouped together because they share a common use, whatever that use may be. Well, they dont have to have something in common, but putting unrelated things together is not really good practice! Its like having a filing cabinet and putting all of the paper in random positions. Whats the need for the grouping abilities of a filing cabinet if you do that? Enough of the though, Im sure you want some code. This is a declaration of an array of integer variables:


int a[5];


You can see that an array looks a lot like a normal variable, but it has some square brackets at the end. When you declare an array, these brackets are filled with the size of the array you want; the number of variables that you are going to store in it. In this case, we wanted 5 integer variables. An array can pretty much be whatever size you want, if you have the RAM to spare, but it can only hold one type of variable at a time. The variable type can be any that you would normally use, however. We have already covered quite a few.
Accessing a specific variable in the array is easy too; you just put in square brackets the number of the variable you want, like a numbered list. So for the first variable you put [0], for the second you put [1], and so onbut wait. Why is the first variable numbered 0? Well, this is a little quirk of C++ (and most programming languages in general, really) that makes it odd for people who arent used to it; things are labelled 0, 1, 2, 3... not 1, 2, 3, 4... This makes sense if you think about how a computer understands numbers; if you have an array with 8 items, then if you started with 1 the computer could only access 7 places. (1-7; binary, remember?) Of course, the logical thing to do would be to let it use 0 as well. If you let it use 0 however, then 0 must be the first variable, not 1. Besides, how would you handle accessing the variable before the first one in the list? That would be confusing. Heres an example:


int a[5];
 
// Set the first variable in a to 1
a[0] = 1;
 
// Set the second variable in a to 4
a[1] = 4;
 
// Output the first variable
cout << a[0];


One thing you mustnt do (although it is easy to do so, as discussed above) is access a variable in the array that either doesnt exist, such as the 10th variable in an array with 5 places, or hasnt had a variable assigned to it. If the second case, you would get a so called garbage value, since the value it returns is just that, garbage. (In some cases you may simply get 0 however) You can try it if you wish, but heres a screenshot of a possible result:

[ Register or Signin to view external links. ]

In the first case however, you will get a segmentation fault, so called because the program is trying to access a segment of memory that it is not allowed to access. This will probably result in your program unexpectedly terminating, possibly along with an error report, depending on the operating system.
To avoid the second of these, it is good practice to initialise all of the places in your array before you start using it. Like a normal variable, you can do this when you define it;


int a[5] = { 0, 0, 0, 0, 0 };


It is important to note the curly brackets. Every item in these brackets, separated by commas, is assigned to its respective variable in the array; the first variable is set to whatever the first value is between the brackets, the second variable to the second value and so on. If you dont fill up all of the spaces, then every variable in the array that you didnt give a value to will be set to 0. For example,


int a[5] = { 1 };


The first entry in this array will be 1, the rest will be 0.
You may have realised by now that arrays can be very useful. A common usage is making them into an actual list; perhaps the ages of a group of people or their gender, or, as we will learn later, using them as co-ordinate spaces for maps or large tables.

So far we have looked at just one type of array; the one-dimensional array. This is useful for linear lists of things, but what if you want an array to store information about a map? For this you would ideally* need two dimensions. How would you do that in C++? Well, its actually very easy; just add another set of square brackets right after the first, like this:

int array[4][5];


Here weve declared a two-dimensional array where one dimension is 4 integers long and the other is 5. Since thinking of arrays as a physical map is just an analogy, ther concept of height and width are just an illusion; this array could be 45, or it could be 54. Of course normal convention is to speak of things in terms of x and then y, and so here we can say that it has a width of 4 and height of 5.

Accessing this array is identical to accessing a one-dimensional array, except where we would use a single set of square brackets we now use two, e.g:


cout << array[0][1];


And they say C++ is difficult! Here were just printing the integer in the first row and second column, or to continue our previous analogy, the map square (0, 1).

You can mass-define two-dimensional arrays in the same way as one-dimensional ones, except now you include another set of curly brackets, like this:


int array[2][2] = { {0, 0}, {1, 1} };


That may look complicated, but what its doing is just setting the first row to be 0, 0, and the second row to be 1, 1. Again, once you remember to pair up the brackets, its easy.

If you want to iterate through a 2-dimensional array, then you can just nest two for loops inside each other, like so


int array[4][4];
 
for(int y = 0; y < 4; ++y)
{
    for(int x = 0; x < 4; ++x)
    {
        array[y][x] = x+y;
    }
}


Note here that I havent followed the convention that I just stated above. There is an important technical reason for this. Due to the way that C++ handles 2-dimensional arrays, it is more efficient if you increment the right-most array index in the inside loop** In plain English my loops are saying For each row, go through each column, then move to the next row; I am increasing my y in the outermost loop and my x in the innermost loop. Because of this my x should be in the right-most array index, so the point (0, 1) is actually the point [1][0]. This is quite counterintuitive, but it is important to remember.

C++ also has a rather neat ability that allows you to not specify an array size; instead you just put some empty square brackets. The size of the array must be known at compile time, so the compiler counts up the number of elements you initialised it with and sets the size of the array accordingly. Very useful if you have a large array of items and you dont want to count the all!


// This array will be 5 elements long
int array[] = { 0, 1, 2, 3, 4 };


Note that although this means that you can create an array with an unknown size at compile time, you cannot create one like this with an unknown size at runtime! Thats called a dynamic array, and again is to do with pointers.

C++ is a lot more powerful than this however, and supports n-dimensional arrays, that is, arrays with any number of dimensions you like. Youre likely to not need to use this feature to create higher than three-dimensional arrays, since our brains are too primitive to accurately picture anything more, but there are cases when you can indirectly do so, and for good reason. I wont get into this further for now, as it can be rather mind-bending, but lets just say its possible to have an array of arrays. Of arrays.

Ratings

Current rating: 6.80 by 5 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"C++ Beginners Tutorial: Arrays." :: Login/Create an Account :: 0 comments

If you would like to post a comment please signin to your account or register for an account.