C++ One-Dimensional Arrays

A one-dimensional array in C++ is a collection of elements of the same data type stored in contiguous memory locations. It allows storing multiple values under a single variable name.

1. Array Declaration

An array is declared by specifying the data type, array name, and size.

C++
Syntax of array declaration
data_type array_name[size];

// Example
int numbers[5];

2. Array Initialization

Arrays can be initialized at the time of declaration.

C++
Example: Array initialization
int numbers[5] = {10, 20, 30, 40, 50};

// Size can be omitted if values are provided
int values[] = {1, 2, 3, 4};

3. Accessing Array Elements

Array elements are accessed using index numbers. Indexing starts from 0.

C++
Example: Accessing array elements
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    
    cout << "First element: " << numbers[0] << endl;
    cout << "Third element: " << numbers[2] << endl;
    
    return 0;
}

4. Looping Through an Array

You can use loops to access all elements of an array.

C++
Example: Loop through array
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

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

5. Common Mistakes

1. Accessing array elements outside the valid index range. 2. Forgetting that array indexing starts from 0. 3. Not initializing array elements before use.

Conclusion

C++ one-dimensional arrays allow efficient storage and access of multiple values of the same type. Understanding declaration, initialization, and indexing is essential for working with arrays.