In this tutorial, you will learn how to get array length in C++.
In C++, you can use the size()
method to get the array length. Below is the syntax of the size() method:
Syntax
arrayname.size()
Initialize Array in C++
array<int,8> a = { 1, 5, 2, 4, 3, 6, 8, 7 };
Using size() Method in C++
The following C++ code will get and print the length of array a:
cout << "\nSize of array is " << a.size() << endl;
Get Array Length in C++ Example
In the below C++ example, it will print the array length and will loop through the array to print its values:
#include <iostream> #include <array> using namespace std; int main () { array<int,8> a = { 1, 5, 2, 4, 3, 6, 8, 7 }; cout << "\nLength of array is " << a.size() << endl; auto pos = a.begin(); cout << endl; while ( pos != a.end() ) cout << *pos++ << "\t"; cout << endl; return 0; }
Output
Length of array is 8 1 5 2 4 3 6 8 7