C++ Arrays
In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. An array is defined by specifying the data type of its elements, followed by the name of the array and the size of the array in square brackets.
Example:
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int numbers[5]; 7 8 cout << "Enter 5 elements:" << endl; 9 for (int i = 0; i < 5; i++) 10 { 11 cin >> numbers[i]; 12 } 13 14 cout << "The elements of the array are:" << endl; 15 for (int i = 0; i < 5; i++) 16 { 17 cout << numbers[i] << endl; 18 } 19 20 return 0; 21}
Output:
1Enter 5 elements: 21 32 43 54 65 7The elements of the array are: 81 92 103 114 125
In C++, arrays are zero-indexed, which means that the first element of the array is located at index 0, the second element at index 1, and so on. The size of the array must be a positive integer constant, and it cannot be changed after the array has been declared.
Arrays can also be initialized when they are declared by specifying the values of their elements in curly braces.
Example:
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int numbers[] = {1, 2, 3, 4, 5}; 7 8 cout << "The elements of the array are:" << endl; 9 for (int i = 0; i < 5; i++) 10 { 11 cout << numbers[i] << endl; 12 } 13 14 return 0; 15}
Output:
1The elements of the array are: 21 32 43 54 65