Arrays in C++
Arrays in C++
Arrays in C++is defined as a collection of similar data items stored at adjoining memory locations. It is used to store collection of primitive data types such as int, float, double, char, etc of any particular type. Arrays stores the fixed size sequential collection of similar data type.
Array declaration in C++
type arrayName [ arraySize ];
Example of array in C++
int arr1[10];
Here,
- int – type of element
- arr– name of the array
- 10 – size of the array
Accessing Array Elements
Each element in an array is connect with a number this number is called as an array index. For accessing elements of an array by using indices.
Syntax of accessing array element
array[index];
Example of Accessing array elements
double salary = balance[9];
C++ Array Initialization
In C++ programming it is possible to initialize an array during declaration.
Example of array initialization
int x[5] = {1,2,3,4,5};
Program of array initialization
include <iostream> using namespace std; int main() { int numbers[5] = {1,2,3,4,5}; cout << "Enter the numbers: "; for (const int &n : numbers) { cout << n << " "; } cout << "\nThe numbers are: "; for (int i = 0; i < 5; ++i) { cout << numbers[i] << " "; } return 0; }
Output
Enter the numbers: 1 2 3 4 5 The numbers are: 1 2 3 4 5
Advantages of C++ Array
- Code Optimization
- Random Access
- Easy to traverse data
- Easy to manipulate data
- Easy to sort data etc.
Disadvantages of C++ Array
- Fixed size
Read more, Return by Reference in C++