Arrays - sheerazwalid/COMP-I GitHub Wiki

Single dimensional arrays

An array is a sequence of values stored in computer memory. The following code shows one way to declare an array a and initialize it to store the integers 3, 22, 5, 14 and 6 in that order.

int a[] = { 3, 22, 5, 14, 6 };

Values in the array are indexed starting with 0. So for the above example, the value in position 0 is 3, the value in position 1 is 22, the value in position 2 is 5, and so on.

You can access the values in an array using the syntax a[i] where i is an integer greater than or equal to 0 and less than the number of values in the array. The following code will print all of the values of the example array give above.

cout << a[0];  // prints 3
cout << a[1];  // prints 22
cout << a[2];  // prints 5
cout << a[3];  // prints 14
cout << a[4];  // prints 6

Often, one uses a loop to access the values in an array. The following code shows an alternative way to print the 5 values in the array a given above using a for loop. Notice that the index is now an integer variable rather than a integer literal.

for (int i = 0; i < 5; ++i) {
    cout << a[i];
}

Arrays can also be created without being initialized. For example, the following code create an array b of double precision floating point numbers of size 40.

double b[40];

If you want to initialize the values of b to zeros, you could use the following statement.

double b[40] = { 0 };

You can change the values in an array using the assignment operator. The following illustrates how to assign the value 3.14 to position 3 in array b.

b[3] = 3.14;

Multi-dimensional arrays

In addition to arrays with one dimension, you can also have arrays of 2 or more dimensions. The following illustrates how to define a 2-dimensional array a of int initialized to all zeros. In this example, a has 30 rows and 40 columns.

int a[30][40] = { 0 };

The following code checks that each value in a is a zero.

#include <iostream>
#include <cassert>

using namespace std;

int main() {
    int a[30][40] = { 0 };

    for (int r = 0; r < 30; ++r) {
        for (int c = 0; c < 40; ++c) {
            assert(a[r][c] == 0);
        }
    }
    return 0;
}

Additional reading

Optional Videos

⚠️ **GitHub.com Fallback** ⚠️