Array Basics in C++

An array is used to store multiple values of the same type. An element in an array can be accessed using an index.

An array is used to store a collection of data, but often it is more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as numberO, numberl, . . . , and number99, you declare one array with a name such as num­bers and use numbers[0], numbers[1], . . . , and numbers[99] to represent individual variables. This section introduces how to declare arrays and access array elements using indexes.

1. Declaring Arrays

To declare an array, you need to specify its element type and size using the following syntax:

elementType arrayName[SIZE];

The elementType can be any data type, and all elements in the array will have the same data type. The SIZE, known as array size declarator, must be an expression that evaluates to a constant integer greater than zero. For example, the following statement declares an array of 10 double elements:

double myList[10];

The compiler allocates the space for 10 double elements for array myList. When an array is declared, its elements are assigned arbitrary values. To assign values we use the following syntax:

arrayName[index] = value;

For example, the following code initializes the array:

myList[0] = 5.6;
myList[
1] = 4.5;
myList[
2] = 3.3;
myList[
3] = 13.2;
myList[
4] = 4.0;
myList[
5] = 34.33;
myList[
6] = 34.0;
myList[
7] = 45.45;
myList[
8] = 99.993;
myList[
9] = 111.23;

The array is pictured in Figure 7.1.

Figure 7.1 The array myList has 10 elements of double type and int indices from 0 to 9

2. Accessing Array Elements

The array elements are accessed through the integer index. Array indices are 0-based; that is, they run from 0 to arraySize-1. The first element is assigned the index 0, the second element is assigned 1, and so on. In the example in Figure 7.1, myList holds 10 double values, and the indices are from 0 to 9.

Each element in the array is represented using the following syntax:

arrayName[index];

For example, myList[9] represents the last element in the array myList. Note that the size declarator is used to indicate the number of elements when declaring the array. An array index is used to access a specific element in an array.

Each element in the array, when accessed by its index, can be used in the same way as a regular variable. For example, the following code adds the values in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

The following code increments myList[0] by 1:

myList[0]++;

The following code invokes the max function to return the larger number between myList[1] and myList[2]:

cout << max(myList[1], myList[1]) << endl;

The following loop assigns 0 to myList[0], 1 to myList[1], . . . , and 9 to myList[9]:

for (int i = 0; i < 10; i++)

{

myList[i] = i;

}

3. Array Initializers

C++ has a shorthand notation, known as the array initializer, which declares and initializes an array in a single statement, using the following syntax:

elementType arrayName[arraySize] = {valueO, valuel, …, valuek};

For example,

double myList[4] = {1.9, 2.9, 3.4, 3.5};

This statement declares and initializes the array myList with four elements, making it equiva­lent to the statements shown below:

double myList[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

4. Processing Arrays

When processing array elements, you will often use a for loop—for the following reasons:

  • All of the elements in an array are of the same type. They are evenly processed in the same way using a loop.
  • Since the size of the array is known, it is natural to use a for

Assume the array is declared as follows:

const int ARRAY_SIZE = 10;

double myList[ARRAY_SIZE];

Here are 10 examples of processing arrays:

  1. Initialing arrays with input values: The following loop initializes the array myList with user input values:

cout << “Enter ” << ARRAY_SIZE << ” values: “;

for (int i = 0; i < ARRAY_SIZE; i++)

cin >> myList[i];

  1. Initializing arrays with random values: The following loop initializes the array myList with random values between 0 and 99:

for (int i = 0; i < ARRAY_SIZE; i++)

{

myList[i] = rand() % 100;

}

  1. Printing arrays: To print an array, you must print each element in it, using a loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)

{

cout << myList[i] << ” “;

}

  1. Copying arrays: Suppose you have two arrays, list and myList. Can you copy myList to list using a syntax like the following?

list = myList;

This is not allowed in C++. You must copy individual elements from one array to the other as follows:

for (int i = 0; i < ARRAY_SIZE; i++)

{

list[i] = myList[i];

}

  1. Summing all elements: Use a variable named total to store the sum. Initially, total is 0. Add each element in the array to total using a loop like this:

double total = 0;

for (int i = 0; i < ARRAY_SIZE; i++)

{

total += myList[i];

}

  1. Finding the largest element: Use a variable named max to store the largest element. Ini­tially, max is myList[0]. To find the largest element in the array myList, compare each element in it with max, and then update max if the element is greater than max.

double max = myList[0];

for (int i = 1; i < ARRAY_SIZE; i++)

{

if (myList[i] > max) max = myList[i];

}

  1. Finding the smallest index of the largest element: Often you need to locate the largest element in an array. If an array has multiple elements with the same largest value, find the smallest index of such an element. Suppose the array myList is {1, 5, 3, 4, 5, 5}. So, the largest element is 5 and the smallest index for 5 is 1. Use a variable named max to store the largest element and a variable named indexOfMax to denote the index of the largest element. Initially max is myList[0] and indexOfMax is 0. Compare each element in myList with max. If the element is greater than max, update max and indexOfMax.

double max = myList[0];

int indexOfMax = 0;

for (int i = 1; i < ARRAY_SIZE; i++)

{

if (myList[i] > max)

{

max = myList[i];

indexOfMax = i;

}

}

What is the consequence if (myList[i] > max) is replaced by (myList [i] >= max)?

  1. Random shuffling: In many applications, you need to reorder the elements in an array randomly. This is called shuffling.
    To accomplish this, for each element myList[i], randomly generate an index j and swap myList[i] with myList[j], as follows:

srand(time(0));

for (int i = ARRAY_SIZE – 1; i > 0; i–)

{

// Generate an index j randomly with 0 <= j <=i

int j = rand() % (i + 1);

// Swap myList[i] with myList[j]

double temp = myList[i];

myList[i] = myList[j]

myList[j] = temp;

}

  1. Shifting elements: Sometimes you need to shift the elements left or right. For example, you may shift the elements one position to the left and fill the last element with the first element:

double temp = myList[0]; // Retain the first element

// Shift elements left

for (int i = 1; i < ARRAY_SIZE; i++)

{

myList[i – 1] = myList[i];

}

// Move the first element to fill in the last position

myList[ARRAY_SIZE – 1] = temp;

10. Simplifying coding: Arrays can be used to simplify coding for certain tasks. For exam­ple, suppose you want to obtain the English name of a given month by its number. If the month names are stored in an array, the month name for a given month can be accessed simply via the index. The following code prompts the user to enter a month number and displays its month name:

string months[] = {“January”, “February”, …, “December”};

cout << “Enter a month number (1 to 12): “;

int monthNumber;

cin >> monthNumber;

cout << “The month is ” << months[monthNumber – 1] << endl;

If you didn’t use the months array, you would have to determine the month name using a lengthy multiway if-else statement as follows:

if (monthNumber == 1)

cout << “The month is January” << endl;

else if (monthNumber == 2)

cout << “The month is February” << endl;

else

cout << “The month is December” << endl;

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *