C++ Length of Array

Array length denotes the number of elements in the array.

To find the array length in C++, there is no direct builtin function or property, but you can use Foreach statement.

In this tutorial, we will learn how to use C++ Foreach to find the length of an array.

Example 1: Find length of Integer Array

In this example, we shall take an array of numbers, and a counter named len initialized to zero. We then write Foreach statement to run for each element in the array. During each iteration we shall increment the counter.

After the completion of Foreach statement, the counter contains the number of elements in the array.

C++ Program

#include <iostream>
using namespace std;

int main() {
   int arr[] = {3, 5, 8, 13, 21, 34};
   int len = 0;

   for (int n: arr)
      len++;

   cout << len;
}

Output

6

Example 2: Length of Empty Array

Let us check if we would zero as length for an empty array.

C++ Program

#include <iostream>
using namespace std;

int main() {
   int arr[] = {};
   int len = 0;

   for (int n: arr)
      len++;

   cout << len;
}

Output

0

Conclusion

In this C++ Tutorial, we learned how to find the length of a C++ Array.