5. DSA with C++ - Arrays data structure

Arrays Explanation

In C++, an array is a fixed-size collection of elements of the same data type, stored in contiguous memory locations. It provides a way to store and access multiple values of the same type using a single identifier.
  1. Declaration and Initialization: To declare an array in C++, you specify the data type of its elements, followed by the array name and the size of the array enclosed in square brackets [].
     
    int numbers[5]; // Declaration of an integer array of size 5
          
  2. You can also initialize the array at the time of declaration by providing a comma-separated list of values enclosed in curly braces {}.
     
    int numbers[5] = {1, 2, 3, 4, 5}; // Declaration and initialization of an integer array
          
  3. Accessing Array Elements: Array elements can be accessed using their index, which starts at 0 for the first element. The index is enclosed in square brackets after the array name.
     
    int x = numbers[2]; // Accessing the third element of the array
          
  4. Array Size: The size of an array is fixed and cannot be changed once it is declared. The size of the array can be determined using the `sizeof()` operator, which returns the size in bytes.
     
    int size = sizeof(numbers) / sizeof(numbers[0]); // Calculating the size of the array
          
  5. Iterating over Array Elements: You can use loops, such as the `for` loop, to iterate over the elements of an array.
     
    for (int i = 0; i < size; i++) {
      cout << numbers[i] << " "; // Printing each element of the array
    }
          
  6. Arrays and Pointers: In C++, the name of the array acts as a pointer to its first element. You can use pointer arithmetic to access array elements.
     
    int* ptr = numbers; // Assigning the pointer to the array
    int x = *(ptr + 2); // Accessing the third element of the array using pointer arithmetic
          
Arrays are a fundamental data structure in C++ and are widely used for storing and manipulating collections of data. Understanding array syntax, initialization, element access, size calculation, iteration, and the relationship between arrays and pointers will help you effectively work with arrays in C++.