In C++, arrays are used to store multiple values of the same data type in a single variable.
Arrays are essential in C++ as they allow you to work with collections of data efficiently.
The elements of an array are stored in contiguous memory locations, which enables fast access to each element.
Basic Syntax
DataType arrayName[arraySize];
1. Declaring and Initializing Arrays
You can declare and initialize arrays in a single statement.
#include <iostream> using namespace std; int main() { // Declare and initialize an array int numbers[5] = {10, 20, 30, 40, 50}; // Access and display elements for (int i = 0; i < 5; i++) { cout << "Element at index " << i << ": " << numbers[i] << endl; } return 0; }
Explanation:
- int numbers[5] creates an integer array of size 5.
- numbers[i] accesses each element at index i.
Output:
Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 4: 50
2. Default Initialization of Arrays
If you declare an array without initializing it, the values are indeterminate. However, if you initialize only a few elements, the rest are set to 0.
#include <iostream> using namespace std; int main() { int numbers[5] = {1, 2}; // Partially initialized array for (int i = 0; i < 5; i++) { cout << "Element at index " << i << ": " << numbers[i] << endl; } return 0; }
Explanation:
- Only the first two elements are initialized (1, 2), and the remaining elements default to 0.
Output:
Element at index 0: 1 Element at index 1: 2 Element at index 2: 0 Element at index 3: 0 Element at index 4: 0
3. Accessing Array Elements
You can access elements in an array using their index. Array indices start at 0.
#include <iostream> using namespace std; int main() { int numbers[3] = {5, 10, 15}; cout << "First element: " << numbers[0] << endl; cout << "Second element: " << numbers[1] << endl; cout << "Third element: " << numbers[2] << endl; return 0; }
Output:
First element: 5 Second element: 10 Third element: 15
4. Modifying Array Elements
You can change the value of specific elements in an array by assigning a new value to the array index.
#include <iostream> using namespace std; int main() { int scores[3] = {90, 80, 70}; // Modify elements scores[0] = 95; scores[1] = 85; scores[2] = 75; for (int i = 0; i < 3; i++) { cout << "Score " << i + 1 << ": " << scores[i] << endl; } return 0; }
Output:
Score 1: 95 Score 2: 85 Score 3: 75
5. Finding the Array Length
In C++, you can determine the number of elements in an array by dividing the total size of the array by the size of a single element.
#include <iostream> using namespace std; int main() { int numbers[] = {10, 20, 30, 40, 50}; int length = sizeof(numbers) / sizeof(numbers[0]); cout << "Array length: " << length << endl; return 0; }
Explanation:
- sizeof(numbers) gives the total size of the array in bytes.
- sizeof(numbers[0]) gives the size of a single element.
- Dividing the two yields the number of elements in the array.
Output:
Array length: 5
6. Arrays in Functions
Arrays can be passed to functions, either by specifying the size or by using pointers.
#include <iostream> using namespace std; void displayArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; } int main() { int numbers[] = {1, 2, 3, 4, 5}; int length = sizeof(numbers) / sizeof(numbers[0]); displayArray(numbers, length); return 0; }
Explanation:
- displayArray takes an integer array and its size as parameters, allowing it to display the array contents.
Output:
1 2 3 4 5
7. Multi-dimensional Arrays
Multi-dimensional arrays, such as 2D arrays, are useful for working with tables or matrices.
#include <iostream> using namespace std; int main() { // Initialize a 2D array (3x3) int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Display the 2D array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << matrix[i][j] << " "; } cout << endl; } return 0; }
Explanation:
- matrix[3][3] declares a 2D array with 3 rows and 3 columns.
- Nested loops display each element of the 2D array in a matrix format.
Output:
1 2 3 4 5 6 7 8 9
8. Modifying Elements in a Multi-dimensional Array
You can change individual elements in a multi-dimensional array by accessing them with both indices.
#include <iostream> using namespace std; int main() { int matrix[2][2] = { {10, 20}, {30, 40} }; // Modify elements matrix[0][1] = 25; matrix[1][0] = 35; // Display modified matrix for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cout << matrix[i][j] << " "; } cout << endl; } return 0; }
Output:
10 25 35 40
9. Using std::array for Fixed-size Arrays
std::array (from the <array> library) is a safer, more flexible alternative for fixed-size arrays, providing additional functionality like bounds checking.
#include <iostream> #include <array> using namespace std; int main() { array<int, 5> numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.size(); i++) { cout << "Element " << i << ": " << numbers[i] << endl; } return 0; }
Explanation:
- std::array<int, 5> is a fixed-size array of 5 integers.
- numbers.size() provides the size of the array.
Output:
Element 0: 1 Element 1: 2 Element 2: 3 Element 3: 4 Element 4: 5
10. Using Arrays with std::vector
std::vector from the <vector> library is a dynamic array that can resize itself, providing greater flexibility than fixed-size arrays.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> numbers = {10, 20, 30, 40, 50}; numbers.push_back(60); // Add an element for (int i = 0; i < numbers.size(); i++) { cout << "Element " << i << ": " << numbers[i] << endl; } return 0; }
Explanation:
- vector<int> numbers creates a dynamic array (vector).
- push_back() adds an element to the end of the vector.
Output:
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50 Element 5: 60
11. Initializing Arrays with Loops
You can initialize an array using a loop, which is useful for assigning calculated values.
#include <iostream> using namespace std; int main() { int squares[5]; // Initialize array with squares of indices for (int i = 0; i < 5; i++) { squares[i] = i * i; } for (int i = 0; i < 5; i++) { cout << "squares[" << i << "] = " << squares[i] << endl; } return 0; }
Explanation:
- squares[i] = i * i assigns the square of i to each element.
Output:
squares[0] = 0 squares[1] = 1 squares[2] = 4 squares[3] = 9 squares[4] = 16
12. Arrays of Strings
Arrays can also hold strings, making it easy to store multiple words or phrases.
#include <iostream> #include <string> using namespace std; int main() { string fruits[3] = {"Apple", "Banana", "Cherry"}; for (int i = 0; i < 3; i++) { cout << "Fruit " << i + 1 << ": " << fruits[i] << endl; } return 0; }
Explanation:
- string fruits[3] creates an array of 3 strings.
Output:
Fruit 1: Apple Fruit 2: Banana Fruit 3: Cherry
Summary Table of Common Array Operations
Operation | Example Code | Description |
---|---|---|
Declare and Initialize | int arr[5] = {1, 2, 3}; | Declares and initializes an array |
Access Element | arr[0] | Accesses element at index 0 |
Modify Element | arr[1] = 5; | Changes value at index 1 |
Find Array Length | sizeof(arr) / sizeof(arr[0]) | Calculates array length |
Pass to Function | void func(int arr[], int size) | Passes array as parameter |
Multi-dimensional Array | int mat[3][3] = {…}; | Declares a 2D array |
Modify 2D Array | mat[1][1] = 0; | Changes value at specific row and column |
Using std::array | array<int, 5> arr = {1, 2, 3, 4, 5}; | Fixed-size array with additional functionality |
Using std::vector | vector<int> vec = {1, 2, 3}; vec.push_back(4); | Dynamic array with resizing |
Loop Initialization | for (int i = 0; i < n; i++) arr[i] = i * i; | Initializes array with calculated values |
Array of Strings | string arr[3] = {“A”, “B”, “C”}; | Stores multiple strings in an array |
Key Takeaways
- Arrays in C++ are useful for storing collections of data in contiguous memory.
- You can use fixed-size arrays with std::array or dynamic arrays with std::vector.
- 2D arrays are useful for matrices and tables, and arrays of strings are effective for storing text data.
- Arrays can be passed to functions and initialized with loops, enabling flexible data manipulation.