Array In C++ Example

4 min read Jun 28, 2024
Array In C++ Example

Arrays in C++: A Comprehensive Guide with Examples

Arrays are fundamental data structures in C++ that allow you to store a collection of elements of the same data type. They provide a convenient way to organize and access data in a sequential manner. This article will delve into the intricacies of arrays in C++, covering their declaration, initialization, access, and manipulation, all illustrated with clear examples.

Declaration and Initialization

To declare an array, you specify the data type of its elements followed by the array name and the size enclosed in square brackets:

data_type array_name[size];

Example:

int numbers[5]; // Declares an array named 'numbers' to hold 5 integers

You can initialize an array during declaration:

int numbers[5] = {1, 2, 3, 4, 5}; // Initializing with values

Alternatively, you can initialize it later:

int numbers[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

Accessing Array Elements

Individual elements in an array are accessed using their index, starting from 0 for the first element.

Example:

int numbers[5] = {1, 2, 3, 4, 5};
cout << numbers[0]; // Output: 1
cout << numbers[3]; // Output: 4

Array Manipulation

1. Assigning Values:

int numbers[5] = {1, 2, 3, 4, 5};
numbers[2] = 10; // Change the third element to 10

2. Looping Through Elements:

You can use a for loop to iterate over all elements in an array:

int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
    cout << numbers[i] << " "; // Output: 1 2 3 4 5
}

3. Passing Arrays to Functions:

Arrays can be passed to functions as arguments. However, C++ uses pass-by-reference for arrays, meaning any changes made to the array inside the function will affect the original array.

Example:

void printArray(int arr[], int size) {
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    printArray(numbers, 5); // Output: 1 2 3 4 5 
    return 0;
}

Multidimensional Arrays

C++ supports multidimensional arrays, which can represent tabular data like matrices.

Example:

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; // A 2x3 matrix

Conclusion

Arrays are essential tools in C++ for storing and managing collections of data. This article has provided a thorough overview of their declaration, initialization, access, and manipulation techniques. With these fundamental concepts, you can effectively leverage arrays in your C++ programs.

Latest Posts