find the length of array in C++ | applied electronics engineering

# find the length of array in C++

By Applied Electronics - Saturday, June 4, 2016 No Comments
Unlike in many programming language such as python or javascript, C++ programming language has no function or method to find out the length of an array. In python if A is an array, len(A) gives the number of elements. Similarly A.length gives the length of array in javascript. In C++ we don't have this kind of functions. In C++ we need to find the length of array using the sizeof( ) function. sizeof( ) takes parameter such as variables of type int, float, double, char or array and returns the size of that variable in bytes. In case of array dividing the total bytes consumed by an array by the the byte size of one element of the array gives us the number of elements.

So in C++ we can do the following to find the array length.

no. of elements = sizeof(A)/sizeof(A[0])

where A is an array and A[0] is the first element.

Consider the following example code:
#include

using namespace std;

int main(){

int A[4] = {1,2,3,4};
int Alen = sizeof(A)/sizeof(A[0]);
int i;

cout << "length of array A: " << Alen << "\n";

for (i = 0; i < Alen; i++){

cout << "A[" << i << "] is " << A[i] << endl;

}

}

In the above code, Alen is the length of the array.

The output is-