C++ Arrays


Go to main Page

Arrays in C++

In this tutorial we are going to learn about arrays with the help of examples.

In c++ array is a variable to store multiple values of the same type.

For example, there are 40 students in class and you want to store their names you will use an array.

Syntax

double student[40];

Here a student is an array which is holding 40 students of double type.

Syntax for array declaration.

dataType arrayName[arraySize];

For example

int z[6];

How to access elements in array?

In C++ programming each element of the array is associated with the number. We can access the element with the help of that number.

Diagram
Things you need to know about arrays
  1. The array indices start with 0
  2. If the size of array is n than its index is n-1

How to initialize array?

We can also initialize array at the time of declaration

Syntax

int x[6] = {19, 20, 21, 22, 23, 24};

Diagram

How to take userinput in array?

For use input you have to use cin.

Example

int mark[5] = {19, 10, 8, 17, 9};
mark[3] = 9;
// store the value at third position
cin >> mark[2];
cin >> mark[i-1];
cout << mark[0];
cout >> mark[i-1];


How to display in array?

For use input you have to use cout.

Example

#include <iostream>
using namespace std;
int main() {
    int numbers[5] = {7, 5, 6, 12, 35};

    cout << "The numbers are: ";
    for (const int &n : numbers) {
        cout << n << "  ";
    }


    cout << "\nThe numbers are: ";
    for (int i = 0; i < 5; ++i) {
        cout << numbers[i] << "  ";
    }

    return 0;
}

Output

The numbers are: 7  5  6  12  35
The numbers are: 7  5  6  12  35

Example : Display Sum and Average of Array Elements Using for Loop


#include <iostream>
using namespace std;

int main() {

    double numbers[] = {7, 5, 6, 12, 35, 27};

    double sum = 0;
    double count = 0;
    double average;

    cout << "The numbers are: ";

    for (const double &n : numbers) {
        cout << n << "  ";
        sum += n;

        ++count;
    }

    cout << "\nTheir Sum = " << sum << endl;

    average = sum / count;
    cout << "Their Average = " << average << endl;

    return 0;
}

Output

The numbers are: 7  5  6  12  35  27
Their Sum = 92
Their Average = 15.3333