In this C++ tutorial, you will learn how to find the length of an array using for loop statement.

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.

Examples

ADVERTISEMENT

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

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.