C++ Arrays

An array in C++ is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to store multiple values using a single variable name and access each element using an index.

Syntax

data_type array_name[array_size];

Where:

  • Array indices start at 0, not 1.
  • All elements in an array must be of the same data type.
  • The size of the array must be known at compile time (for standard arrays).
  • Access elements using the syntax: array_name[index].

Next Topic

Next, learn about Multidimensional Arrays in C++.

  • data_type – Type of elements stored in the array (e.g., int, float, char).
  • array_name – Name of the array.
  • array_size – Number of elements the array can hold (must be a constant value).

Example: Declaring and Initializing an Array

#include <iostream>
using namespace std;

int main() {

    int numbers[5] = {10, 20, 30, 40, 50}; // Array initialization

    // Accessing array elements
    for(int i = 0; i < 5; i++) {
        cout << "Element " << i << ": " << numbers[i] << endl;
    }

    return 0;
}

Output

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Key Points About Arrays

  • Array indices start at 0, not 1.
  • All elements in an array must be of the same data type.
  • The size of the array must be known at compile time (for standard arrays).
  • Access elements using the syntax: array_name[index].

Next Topic

Next, learn about Multidimensional Arrays in C++.