Creating and using an Array

<< Click to Display Table of Contents >>

Navigation:  Concordance Programming Fundamentals > Declaring and using a Variable >

Creating and using an Array

In addition to variables that hold single values, you can also create variables that hold multiple values, called an array. You declare an array in a similar manner to a normal variable. However, in order to access the array, you must know where in the array your value exists. In this sense, an array is like an apartment building: in order to speak with someone who lives in an apartment, you need to know their apartment number.

To declare an array

1.Determine the type of data the array will hold, such as int or text.

i.Like other variables, an array can hold data of only one type: an array can hold multiple values of that type. For more information on variable types, see About Variable Types and Data Types in the CPL Language Reference.

2.Declare the name of the variable, as you would any other variable.

i.For more information on declaring a variable, see Declaring a Variable.

3.Follow the variable name with the size of the array, in square brackets [].

i.You must define the size of the array before you start adding information to the array. Once you have declared the size, you may not change the size: this is known as a static array. (Other programming languages support dynamic arrays, which can change size.)

ii.The following example show several different types of array declarations:

int daysOftheMonth[31];

char myAlphabet[26];

text myHaiku[15];

To assign a value to an array

Place the number of the array unit (or element) within the square brackets, and then assign the value as you would with any other variable.

The following examples show how to assign individual values to an array:

int myMonthlyWinnings[31]

 

myMonthlyWinnings[0] = 100;

myMonthlyWinnings[1] = -20;

myMonthlyWinnings[2] = 50;

...

Note that the numbering of array elements starts at 0, not 1. So in the previous example, valid entries for myMonthlyWinnings[31] would be myMonthlyWinnings[0] through myMonthlyWinnings[30].