Array Implementation in C++
● Arrays are linear data structures that store elements of the same data type in contiguous
memory locations.
● Each element is identified by an index, starting from 0 (zero-based indexing).
● Arrays allow random access (O(1)) to any element using the index.
● They are efficient for operations like sorting, searching, insertion, deletion, traversal, and
updating.
● C++ supports both static arrays (fixed-size, stack memory) and dynamic arrays
(variable-size, heap memory).
● Arrays can be 1D, 2D, or multidimensional (e.g., arr[10], arr[3][4], arr[2][3][4]).
Real-Life Example of array implementation:
Imagine you’re tracking the scores of 30 students in a class. Instead of creating 30 separate
variables like score1, score2, ..., score30, you can store them in a single array: scores[30].
C++ Array Declaration
● Syntax:
dataType arrayName[arraySize];
● Examples:
int numbers[5]; // 1D array of integers
double grades[27]; // 1D array of doubles
int matrix[3][3]; // 2D array
int cube[2][3][4]; // 3D array
● With Initialization:
int x[5] = {1, 2, 3, 4, 5}; // Fully initialized
int y[5] = {1, 2}; // Remaining elements auto-set to 0
int z[] = {10, 20, 30}; // Size inferred as 3
● Accessing/Modifying Elements:
x[2] = 50; // Assign 50 to the third element
cout << x[2]; // Output: 50
● 2D Array Access:
int matrix[2][3] = {{1,2,3}, {4,5,6}};
cout << matrix[1][2]; // Output: 6