WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ Arrays



C++ Arrays

An array is used to store a collection of data but an array as a collection of variables that are all of the same type.


Instead of declaring multiple variables and storing individual values, you can declare a single array to store all the values.

Example

int a[4];

In the example above, variable a was declared as an array of five integer values [specified in square brackets].

You can initialize the array by specifying the values it holds:

int b[4] = {12, 45, 32, 80};

The values are provideArrays in Loops d in a comma separated list, enclosed in {curly braces}.

Initializing Arrays

To access array elements, index the array name by placing the element's index in square brackets following the array name.
int main()
{
    int a[] = {12, 8, 45, 90, 80};

    cout << a[4] << endl;
    // Outputs 80
    
    cout<< a[2] << endl;
    // Outputs 45

    return 0;
}

Accessing Array Elements

Index numbers can be used to assign a new value to an element.

int c[] = {15, 12, 18, 12, 14};
b[2] = 18;

Arrays in Loops

It's occasionally necessary to iterate over the elements of an array, assigning the elements values based on certain calculations.

Arrays in Loops

Let's declare an array, that is going to store 5 integers, and assign a value to each element using the for loop:

int myArr[6];

for(int x=0; x<6; x++) {
  myArr[x] = 26;
}

Each element in the array is assigned the value of 26. The x variable in the for loop is used as the index for the array.

    int myArr[6];

    for(int x=0; x<6; x++) {
        myArr[x] = 26;
 
        cout << x << ": " << myArr[x] << endl;
    }

//Output
/*
0: 26
1: 26
2: 26
3: 26
4: 26
5: 26


*/

Arrays in Calculations

The following code creates a program that uses a for loop to calculate the sum of all elements of an array.

int main()
{
    int arr[] = {15, 28, 89, 587, 1241};
    int sum = 0; 

    for (int x = 0; x < 6; x++) {
        sum += arr[x];
    }

    cout << sum << endl;

    return 0;
}
//Output
1960

In the array, the first element's index is 0, so the for loop initializes the x variable to 0.

Multi-Dimensional Arrays

A multi-dimensional array holds one or more arrays.
type name[size1][size2]...[sizeN];
two-dimensional 2x6 integer array:
int x[2][6];

Two-Dimensional Arrays

Following is an array with 3 rows and 4 columns:
int x[3][4] = {
  {5, 6, 7,8}, // 1st row
  {5, 8, 8,2}, // 2nd row
  {8, 6, 8,7} // 3nd row
};

You can also write the same initialization using just one row.

    int x[3][4] = {{2, 3, 4}, {8, 9, 10},{8, 6, 8,7}};
    int x[3][4] = {{2, 3, 4}, {8, 9, 10},{8, 6, 8,7}};
cout << x[0][8] << endl;

//Outputs 8


Multi-Dimensional Arrays

Arrays can contain an unlimited number of dimensions

string threeD[8][6][5];

Arrays more than three dimensions are harder to manage.