Introduction to Arrays
Arrays in C++ are collections of elements of the same data type stored in contiguous memory locations. They allow efficient storage and access of multiple values using a single identifier and index positions. Arrays help organize data logically and can be single or multi-dimensional based on the application.
They are commonly used when working with large datasets where dynamic memory allocation is not required. C++ supports arrays of basic, derived, or user-defined data types and allows static and dynamic array creation.
Types of Arrays
- One-Dimensional Arrays
These represent a simple list of elements of the same type stored in sequence.
Syntax:
int arr[5];
Example:
int marks[5] = {90, 85, 88, 92, 76};
- Two-Dimensional Arrays
These represent tables or matrices with rows and columns.
Syntax:
int arr[3][3];
Example:
int matrix[2][2] = {{1, 2}, {3, 4}};
- Multi-Dimensional Arrays
Arrays with more than two dimensions, used in complex simulations or mathematical computations.
Syntax:
int arr[2][3][4];
Example:
int arr[2][3][4] = {
{ {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} },
{ {13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24} } };
cout << arr[1][2][3]; // Output: 24
- Character Arrays (Strings)
Used to store a sequence of characters terminated by a null character \0.
Syntax:
char name[10];
Example:
char name[] = “Alice”;
- Dynamic Arrays (using Pointers)
Used when array size is not known at compile-time.
Syntax:
int* arr = new int[n];
Example:
int* arr = new int[5];
8.3 Accessing and Modifying Array Elements
Elements are accessed using indices starting from 0.
Syntax:
array[index] = value;
Example:
marks[2] = 100; // Modifies the 3rd element
cout << marks[2];
8.4 Traversing Arrays
Looping constructs like for or while are used to traverse arrays.
Example:
for(int i = 0; i < 5; i++) {
cout << marks[i] << ” “;
}
8.5 Arrays as Function Arguments
Arrays can be passed to functions by reference using pointer syntax.
Syntax:
void printArray(int arr[], int size);
Example:
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << ” “;
}
}
8.6 Initialization Techniques
Arrays can be initialized during declaration or later by assigning values to individual elements.
Example:
int numbers[5] = {10, 20, 30, 40, 50};