C++ Arrays
In C++, an array is a collection of elements of the same type, stored in contiguous memory locations. Arrays allow you to store multiple values of a single data type under a single variable name.
1. Declaring and Initializing Arrays
Example of declaring and initializing an array:
#include <iostream>
int main() {
// Declaration and initialization of an integer array
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing elements of the array
std::cout << "First element: " << numbers[0] << std::endl;
std::cout << "Second element: " << numbers[1] << std::endl;
return 0;
}
2. Accessing Array Elements
You can access elements of an array using index notation (starting from 0):
#include <iostream>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; ++i) {
std::cout << "Element at index " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
3. Array Size and Iteration
You can determine the size of an array using the sizeof
operator:
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < size; ++i) {
std::cout << "Element at index " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
4. Multidimensional Arrays
Example of declaring and using a multidimensional array:
#include <iostream>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements of the multidimensional array
std::cout << "Element at position (1, 2): " << matrix[1][2] << std::endl;
return 0;
}
Conclusion
Arrays in C++ are fundamental data structures that allow you to store and manipulate multiple values of the same type efficiently. This chapter covered basic array operations such as declaration, initialization, accessing elements, determining array size, and using multidimensional arrays. Understanding arrays enables you to manage collections of data effectively in your C++ programs.