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.
A single-dimensional array is essentially a list of elements. For example:
int numbers[5] = {1, 2, 3, 4, 5}; // An array of integers
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " " ;
}
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}
};
cout << matrix[1][2]; // Output: 7
• 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.
• 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.
<#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;
}
10 20 35 40 50
<#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;
}
1 2 3
4 5 6
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
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