Tutorial

Find Array Length in C++

Updated on April 22, 2024
author

Sneh

Find Array Length in C++

Introduction

In this article, we are going to learn various ways through which we can find array length in C++. The length of an array refers to the total number of elements present in the corresponding array. For example, take a look at the array below:

int array1[] = { 0, 1, 2, 3, 4 }

The size or length of the array here is equal to the total number of elements in it - which is 5.

Ways to find Length of an Array in C++

There are a few methods through which we can determine the length of an array in C++ language. They are:

  1. Counting each element
  2. begin() and end() functions
  3. sizeof() function
  4. size() function in STL
  5. Using Pointers

Now, let us discuss each method one by one with examples and in detail.

1. Counting Each Element

Traversing throughout the given array and simultaneously counting the total number of elements we traversed can give us the array’s length. But if we do not know the array’s length, we cannot use a for loop to traverse the array since a for loop needs a terminating number. This issue can be solved by using a simple for-each loop. Let’s take a look at the code below.

#include<iostream>    
#include<array> 
using namespace std;
int main()
{
   int c;
   int arr[]={1,2,3,4,5,6,7,8,9,0};
   cout<<"The array is: ";
   for(auto i: arr)
   {
   		cout<<i<<" ";
   		c++;
   }
   cout<<"\nThe length of the given Array is: "<<c;
   
   return 0;
}

If we run this code, w ewill get the following output:

Output
The array is: 1 2 3 4 5 6 7 8 9 0 The length of the given Array is: 10

In this code, we traverse the array arr using a for-each loop with i as the iterator. As the loop traverses, c is incremented. When the loop terminates, the c variable contains the number of times the loop was executed, giving the total length of the array.

2. Using begin() and end()

We can also calculate the length of an array using the standard library’s begin() and end() functions. The two functions return iterators pointing to the corresponding array’s start and the end, respectively. Take a look at the given code:

#include<iostream>    
#include<array> 
using namespace std;
int main()
{  
   //Given Array
   int arr[] = { 11, 22, 33, 44 };
   
   cout<<"The Length of the Array is : "<<end(arr)-begin(arr); //length
   
   return 0;
}

The output of this code will be:

Output
The Length of the Array is : 4

Here, we can see the difference between the return values of the two functions end() and begin() gives us the size or length of the given array arr. In this case, the difference is 4, which is the length of arr.

3. Using sizeof() Function to Find Array Length in C++

The sizeof() operator in C++ returns the size of the passed variable or data in bytes, plus the total number of bytes required to store an array. So, if we divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.

Let us take a look at how it works.

#include<iostream>    
#include<array> 
using namespace std;
int main()
{  //Given array
   int  arr[] = {10 ,20 ,30};
   
   int al = sizeof(arr)/sizeof(arr[0]); //length calculation
   cout << "The length of the array is: " <<al;
   
   return 0;
}

The output of this code will be:

Output
The length of the array is: 3

As we can see, we get our desired length as output.

4. Using the size() Function in STL

There is a size() function defined in the standard library that returns the number of elements in the given container(array in our case). We can use this function to return the length in the following way:

#include<iostream>    
#include<array> 
using namespace std;
int main()
{  //Given array
   array<int,5> arr{ 1, 2, 3, 4, 5 };
   //Using the size() function from STL
   cout<<"\nThe length of the given Array is: "<<arr.size();
   return 0;
}

On execution, the above code will return the following output:

Output
The length of the given Array is: 5

5. Using Pointers to Find Array Length in C++

We can also find the length of a given array using pointers. A pointer is a variable that stores the memory address of the object instead of storing the object itself. Let us see how we can use a pointer to get the length of an array.

#include<iostream>    
#include<array> 
using namespace std;
int main()
{  //Given array
   int  arr[6] = {5,4,3,2,1,0};
   
   int len = *(&arr + 1) - arr;
   //*(&arr + 1) is the address of the next memory location
   // just after the last element of the array
   
   cout << "The length of the array is: " << len;
   
   return 0;
}

The output of this code will be:

Output
The length of the array is: 6

The expression *(arr+1) gives us the address of the memory space just after the array’s last element. Hence, the difference between it and the array’s starting location or the base address (arr) gives us the total number of elements in the given array.

Conclusion

In this tutorial, we discussed the various methods to find array length in C++. Even though all methods return the length in one way or the other, we prefer using for-each loop not only because of code readability but also for its cross-platform reliability.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Sneh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel