C++ Arrays

C++ Arrays are the collection of similar data stored in consecutive memory locations. Arrays are handy when dealing with a large amount of similar data.  

Suppose a user wants to store the marks of 100 students and declare 100 variables. It does not make sense. This process can be simplified by using an array.

cpp arrays

Each element can be accessed within an array by using its reference number to its location which is called the index.  Index starts with 0 and ends with length-1.


Syntax: C++ Arrays declaration

data_type array_name [length];

Example

int marks[5];

The maximum length of an array cannot be changed after its declaration.


Syntax: C++ Arrays initialization

This process of assigning value to an array is called array initialization.

data_type array_name [lengh] = {list of values}; 

Example

int marks [5] = {89, 92, 78, 90, 91};

Example: Display array elements

Here is an example to display c++ array elements. The index of the first element of an array is 0, the second element is 1 and this sequence goes on. Check the below example to display elements on each index.

//Arrays in C++
#include <iostream>
using namespace std;

int main() {
int array[5]= {9, 4, 7, 34, 50};

cout << "The array elements are:"<<endl;

    for (int n = 0; n < 5; ++n) {
        cout << array[n] <<endl;
    }
    return 0;
}

Output

The array elements are:
9
4
7
34
50

Recommended Articles

C++ student grade program

C++ program to add N numbers

Scroll to Top