# CSCI 201 Study Aid: Arrays

## The Array concept.

• The fundamental concept of an array in C++ is that of a sequential collection of values, all of the same type, all accessed by the same variable name. Individual values in an array are individually accessed by using the array name and an index (a number) to specify which value is being accessed.
• For example, consider this declaration:
int number;

• This declares one variable of type integer capable of holding a single whole number. A diagram showing this variable's memory allocation would look like this:
+---------+
|         |
+---------+
number

• Compare this to the declaration of an array of integers:
int list[5];

• In this case we have declared an array which is capable of holding 5 integers. The 5 integers are located in the array, next to each other in memory, and indexed (numbered) from the first element (element 0) through to the last element (element 4).
• A diagram representing this array in memory would be:
memory address:  1001       1005      1009     1013      1017      1021
+---------+---------+---------+---------+---------+
|         |         |         |         |         |
+---------+---------+---------+---------+---------+
LIST[0]   LIST[1]   LIST[2]   LIST[3]    LIST[4]

• In C++ (and C) all arrays are indexed from 0 to n-1 where n is the size of the array.
• Arrays can be of any type, for example:
int list[67];    // an array of 67 integers indexed from 0 to 66
char string[20]; // an array of 20 characters indexed from 0 to 19
float price[30]; // an array of floating point numbers indexed
// from 0 to 29

## Array usage

• The elements in an array can be accessed and used by specifying the array name and, in square brackets, the index of the element you want to use. For example, to store 78.54 into the first element of the array price, we would write:
price[0] = 78.54; // Note, first element is index 0

• To store 100.25 into element 5 of the array price, we would write:
price[5] = 100.25; // Note, this is the 6th element

• To print the last element of the array price, we would write:
cout << price[29];

• When this index notation is used to access elements of an array, the individual elements can be treated as individual variables. The following samples show some possibilities:
float total = price[0] + price[1]; // add the first two values

total += price[29]; // add the last value to the total

price[15] *= 2;  // double the price of the 16th value

cout << price[6] - price[8]; // display the difference of two prices

## Simple array processing.

• Because arrays hold more than one piece of data and the elements of an array are indexed, we can, and should, use loops to help process array data.
• In the following example, a while loop is used to allow a user to enter the 10 values which will be stored in an array, and another while loop to add these 10 values. Here is the first part of the program:

// Simple array processing

#include <iostream.h>

void main( void )
{
int list[10]; // an array of 10 integers
int i;        // used as an array index
i = 0;        // always start at 0 for arrays
while( i < 10 ) {
cout << "Enter a whole number for element " << i << " ";
cin >> list[i];  // Note 1
i++;
}

• At this stage in the program the user has entered all 10 values into the array. The line at Note 1 is worth emphasising; the statement
cin >> list[i];

reads a whole number typed at the keyboard by the user and stores it into element i of the array. The variable i takes on new values as the loop executes. For example, when i has a value of 6, the value entered at the keyboard will be stored into element 6 of the array. The statment will execute once for each value of i from 0 to 9 - thus filling the array.
• Now the program continues...
// summing the array
i = 0;          // reset the index to start of array
int total = 0;  // to hold the array sum
while( i < 10 ) {
total += list[i];
i++;
}
cout << "The total of the values in the array is "
<< total << endl;
}//end main

• In this part of the program the same while loop structure has been used to visit each element in the array and add its value into the total.

## Array Initialization

• Arrays can be initialized when they are declared:
int numbers[5]={1, 2, 3, 4, 5};

• When you only initialize a portion of the values in an array, the unspecified values are set equal to 0. For example, in the declaration below:
int numbers[5]={1, 2, 3};

array positions numbers[3] and numbers[4] are set equal to zero.
• You can also use the initial values to specify the size of the array as shown below:
int numbers[]={1, 2, 3, 4};

In this example, the array numbers will have 4 elements corresponding to the 4 initial values.

## Arrays as parameters

• There are two restrictions to the way arrays can be used in functions:
1. A function return type can not be an array
2. An array parameter can only be a reference parameter
• Below is a program in which an array is passed to a function.
#include

int whatIsThis(int [], int);

main()
{
const int arraySize = 10;
int a[arraySize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int result = whatIsThis(a, arraySize);

cout << "Result is " << result << endl;
return 0;
}

int whatIsThis(int b[], int size)
{
return b[size - 1];
}

Notice that following:

• The actual parameter is the name of the array
• The declaration of the formal parameter specifies the data type of the array, but not the size of the array
• A second parameter is used to specify the size of the array (the formal parameter size) so that the function has access to that information.

## Exercises

1. When declaring an array, for example

float the_array[12];

the number specified in the square brackets is:
1. The size of the array.
2. One more than the size of the array.
3. One less than the size of the array.
4. The index of the last element of the array.

2. The first element in an array of size n always has an index of:
1. 1
2. 0
3. n
4. n-1

3. This fragment of code attempts to print the elements of an array. What is logically wrong with the code?

char message[35];
int i = 0;
while( i <= 35 )  {
cout << message[i];
i++;
}

1. The first character printed is element 1.
2. The loop does not traverse the whole array.
3. There is no newline printed after each element.
4. The loop processes past the end of the array.

4. Why are arrays in C++ (and C) indexed from 0?
1. Because it's a natural place to start.
2. Because Kernighan and Ritchie had no fingers.
3. Because that's the way it's gotta be.
4. Because the indexes represent offsets from the first element.

5. Write a program, to declare an integer array of size 12 and initialize the the values of that array. The program should then sum the values stored in that array and print the sum.

6. Write a program that declares an integer array of size 50 and set the array values equal to the even numbers between 2 and 100 in assending order. The program should also print the array values.

7. What is printed by the following program?
// Passing arrays and individual array elements to functions
#include
#include

void modifyArray(int [], int);
void modifyElement(int);

main()
{
const int arraySize = 5;
int a[arraySize] = {0, 1, 2, 3, 4};

cout << "Effects of passing entire array call-by-reference:"
<< endl << endl
<< "The values of the original array are:" << endl;

for (int i = 0; i < arraySize; i++)
cout << a[i];
cout << endl;

modifyArray(a, arraySize);  // array a passed call-by-reference
cout << "The values of the modified array are:" << endl;

for (i = 0; i < arraySize; i++)
cout << a[i];

cout << endl << endl << endl
<< "Effects of passing array element call-by-value:"
<< endl << endl << "The value of a[3] is "
<< a[3] << endl;

modifyElement(a[3]);
cout << "The value of a[3] is " << a[3] << endl;
return 0;
}

void modifyArray(int b[], int sizeOfArray)
{
for (int j = 0; j < sizeOfArray; j++)
b[j] *= 2;
}

void modifyElement(int e)
{
cout << "Value in modifyElement is "
<< (e *= 2) << endl;
}