C++ Arrays

In C++, an array is a collection of elements of the same type, stored in contiguous memory locations. Arrays allow for efficient storage and access of multiple data items using indices.

Types of Arrays in C++

1. Single-Dimensional Array:

A single-dimensional array is essentially a list of elements. For example:

int numbers[5] = {1, 2, 3, 4, 5}; // An array of integers

Traversal:

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

2. Multidimensional Array:

A multidimensional array is an array of arrays. The most common type is the two-dimensional array, which can be thought of as a matrix with rows and columns.

int matrix[3][4] = { // A 3x4 matrix
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Accessing Elements:

cout << matrix[1][2]; // Output: 7

Advantages of C++ Arrays

Code Optimization: Arrays allow for efficient storage and manipulation of large amounts of data with less code.

Random Access: Direct access to any element using its index.

Easy Traversal: Iterating through array elements is straightforward.

Easy Manipulation: Functions and algorithms can be applied to arrays easily.

Easy Sorting: Arrays can be sorted using various algorithms.

Disadvantages of C++ Arrays

Fixed Size: Once an array is defined, its size cannot be changed. This can lead to inefficient memory usage if the array is too large or not fully utilized.

No Bounds Checking: Accessing out-of-bounds indices can lead to undefined behavior and potential crashes.

Example: Single-Dimensional Array

<#include <iostream>>
<using namespace std;>

int main() {
  int numbers[5] = {10, 20, 30, 40, 50}; // Define and initialize an array

  // Access and modify elements
  numbers[2] = 35;

  // Print elements using a loop
  for (int i = 0; i < 5; ++i) {
    cout << numbers[i] << " "; // Output: 10 20 35 40 50
  }
  cout << endl;

  return 0;
}

Output:

10 20 35 40 50

Example: Two-Dimensional Array

<#include <iostream>>
<using namespace std;>

int main() {
  int matrix[2][3] = { // Define and initialize a 2x3 matrix
    {1, 2, 3},
    {4, 5, 6}
  };

  // Print matrix elements
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      cout << matrix[i][j] << " "; // Output: 1 2 3 4 5 6
    }
    cout << endl;
  }

  return 0;
}

Output:

1 2 3
4 5 6

Accessing Out-of-Bounds Array

Accessing elements outside the bounds of an array is undefined behavior and can lead to unpredictable results. For example:

int arr[3] = {1, 2, 3};
cout << arr[5]; // Undefined behavior

Handling Fewer Elements Than Array Size

If you initialize an array with fewer elements than its declared size, the remaining elements are initialized to zero (for basic data types). For example:

int arr[5] = {1, 2, 3}; // Remaining elements (arr[3] and arr[4]) are initialized to 0