Arrays are a widespread concept in many programming languages. Before heading into the details, let’s understand what Arrays are and why they are so important? Suppose we need to make a program to store the names of five fruits, namely orange, mango, banana, apple, and grapes. All the fruits would have the same type, i.e., a string but stored in different 5 variables. We use an array to solve this problem, so an array is a data structure that holds fixed-size elements of the same data type.
Memory Requirements
The size of each block in array depends on the data type of an array. Suppose we take an array of type integer:
// The array hours will hold six integer values
int hours[6]
The values in an array start from 0 as shown in the image.
The size of the array can be calculated by multiplying the number of bytes with array size i.e. 6*4 = 24 bytes is the size of the hours’ array.
So, how do we access elements in an array? The entire array has only one name, i.e., hours. If we refer to the above scenario, each element in the array can be accessed using a subscript that is a number. The use of this subscript is necessary to pinpoint a number. The first element in the array is assigned the subscript 0, the second element is assigned the subscript 1, and so on till the last element. Each element in the hours’ array can be used as a separate integer, as shown.
// The first block in the array gets the value 20
hours[0] = 20
For better understanding of this concept a diagram is shown below:
The question marks have been shown because all the other values are not assigned in the array. Now let’s suppose we want to set the value 30 in the fourth element of the array.
// fourth element of the array has an index 3
hours[3] = 30
The element written between the subscript array is the number used to access the contents of the array.
Input and Displaying Contents of Array
Arrays can easily be read through the cin object and can display results through cout objects, as illustrated through the code below.
// This program stores employee work hours in an int array. It uses // one for loop to input the hours and another for loop to display them. #include <iostream> using namespace std; int main() { const int NUM_EMPLOYEES = 6; int hours[NUM_EMPLOYEES]; // Holds hours worked for 6 employees int count; // Loop counter // Input hours worked by each employee cout << "Enter the hours worked by " << NUM_EMPLOYEES << " employees: "; // for loop iterates 6 times for (count = 0; count < NUM_EMPLOYEES; count++) cin >> hours[count]; // Display the contents of the array cout << "The hours you entered are:"; for (count = 0; count < NUM_EMPLOYEES; count++) cout << " " << hours[count]; cout << endl; return 0; }
In the code above, we have defined the number of employees as 6, and we are storing the hours for 6 employees. The for loop iterates for 6 values and stores each input in the consecutive array as shown.
Let’s suppose we have entered 20, 12, 40, 30, 30, and 15 as input. These values will be saved in the array shown above and displayed using a for loop.
Processing Array Contents
Array content can be processed just like any other variable. For instance, We want to calculate the total pay for a particular employee. We can write the following statement.
pay = hours[3] * rate
Here the pay is calculated for the employee whose working hours are entered at the 3rd index and is actually the fourth employee.
We can also see examples of pre-increment and post-increment, for example:
int count = 3;
//This line increments the index and displays the element present at hours[4]
hours[count++]
//This line increments the value present at index 3 i.e. hours[3]++ = 30+1
hours[count]++
Copy one Array to another
We cannot simply assign one array to another to copy one array’s elements to another. Here, the array behaves a little differently than the standard variable. To set one array to another, we need to copy the contents by referencing each index and assigning it to another array at the same index. This example can be demonstrated by the code shown below.
const int SIZE = 6;
// Both arrays are of the same size
int arrayA[SIZE] = {10, 20, 30, 40, 50, 60};
int arrayB[SIZE] = { 2, 4, 6, 8, 10, 12};
// loop till the size of both arrays and copy the contents of array index by index
for (int index = 0; index < SIZE; index++)
arrayA[index] = arrayB[index];
At index 0 the value of arrayA[0] = arrayB[0] , so the value of arrayA[0] changes to 2 from 10.
Comparing two Arrays
Just as we cannot copy one array to another, we cannot compare one array with another array in just a single statement. If we write arrayA = arrayB, then the operator compares the beginning memory addresses of the two arrays and not the array contents. Thus, the comparison would be false, and the code reports that two arrays are not the same.
The correct way of comparing two arrays is shown below. Here the contents of each index are compared with another and a flag variable is used as a check and becomes false if the content of the array differs.
const int SIZE = 6;
int arrayA[SIZE] = { 5, 10, 15, 20, 25, 70 };
int arrayB[SIZE] = { 5, 10, 15, 20, 25, 30 };
bool arraysEqual = true; // Flag variable
int count = 0; // Loop counter variable
// Determine whether the elements contain the same data
// count should be less than size to avoid index out of bound error
while (arraysEqual && count < SIZE)
{
if (arrayA[count] != arrayB[count])
arraysEqual = false;
count++;
}
// Display the appropriate message
if (arraysEqual)
cout << "The arrays are equal.\n";
else
cout << "The arrays are not equal.\n";
Note: Index out of bound error can occur if the count is greater than the array size. Index out of bound means that the code is trying to access the memory location where the array is not located, and because of this, the program can crash or write garbage values as the contents of the array.
Partially Filled Arrays
Sometimes we want to store elements in an array, but we don’t know the number of elements we have to keep. One solution for this problem could be creating a vast array to hold the most considerable value possible, but our memory is limited, so this isn’t that effective. A better solution would be to use a sentinel loop like the one shown below.
const int SIZE = 100;
int array[SIZE];
int numValues = 0;
// entering a number until the count of numValues becomes 1 less than 100
int number;
cout << "Enter a number or -1 to quit: ";
cin >> number;
while (number != -1 && numValues < SIZE)
{
array[numValues] = number;
numValues++;
cout << "Enter a number or -1 to quit: ";
cin >> number;
}
Conclusion
In this article, we have highlighted the basic construction of an array and the problems it can be useful for. For further articles, we will describe the concept of string arrays and the complex functionality performed through an array.