Using Basic Arrays - C/C++Tutorial

Introduction

A normal variable type, such as an int or float, can only hold a single value at any one time. An array allows you to store many values and access them from within your program. For example, if you were creating a simple game, you might wish to keep track of the top 10 scores. One way to do this would be to use an array.

An array is a data structure which allows you to store many different values of the same type. To create a simple High Score table for the example above, you could use the following code:


int high_scores[10];

This would create an array variable called high_scores, which can contain up to 10 different integer values.

If your program wanted to keep track of the last 50 deposits in to your bank account, you could use an array of floating point values (type float) to hold each of the ammounts like so:


float cash_deposits[50];

Remember: The values you add to the array must be of the same type as the array itself

Setting and retrieving data

One of the first things to understand about arrays is how they store the data you place in them. When we defined the array of high scores, we declared that we wanted to store ten seperate values, each of which would be an integer. The array is stored as a set of 10 integer values

These values can be accessed using an index which points to the value you are interested in, so the following code will store the 3rd value from the array in a variable called my_score:


int my_score = high_scores[2];

No, I have not made a typing error, and yes, the 3rd value of the array is accessed by using an index of 2!!

This is because the position of the first array entry is 0. Because our index starts at 0, our high_scores array runs from 0 to 9, and the cash_deposits array runs from 0 to 49. So, to access the last item in the high_scores table we would use:

int last_score = high_scores[9];

This is an important point to remember when you work with arrays because trying to access values past the end of an array will produce potentially serious errors in your programs.

Remember: Arrays are zero based. Their entries run from 0 to (n - 1), where n is the number of entries in the array.

To set a value in an array, you must indicate which entry to set, again by using the index value of the entry. If your game needs to set a new high score for example, you would do something like this:

high_scores[0] = 98;

This line of code will set the first entry in the high_score array to the value 98.

Summary

Getting and setting the data in an array is simple as long as you remember the points above. As an example, the following code will fill an array with random values and then display them:

int my_array[5];

int index;

for(index = 0; index < 4; index++)
my_array[index] = random(100);

for(index = 0; index < 4; index++)
cout << my_array[index];

 

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.