
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of an Array in C/C++
To find the length of an array in C++, we can use various functions and approaches that we are going to discuss in this article. Finding the length of an array is a very common task and is used in looping through an array, sorting the array, finding maximum and minimum, and in many more scenarios.
In this article, we have an array and our task is to find the length of the array in C++.
Approaches to Find Length of Array
Here is a list of approaches to find the length of an array in C++ which we will be discussing in this article with stepwise explanation and complete example codes.
Using sizeof() Operator
You can use the sizeof() operator to find the length of an array. The typeof() operator determines the size in bytes, so we divide the size of the array by the size of the first element to get the length of the array.
Example
Here is an example implementing the sizeof() operator to find the length of the array:
#include <iostream> using namespace std; int main() { int arr[5] = {4, 1, 8, 2, 9}; int len = sizeof(arr)/sizeof(arr[0]); cout << "The length of the array is: " << len; return 0; }
Using Pointers
In this approach, we have used pointer operators i.e. '&' and '*' to find the length of the array using the steps mentioned below.
- The '&' operator gets the address of the complete array.
- The '&arr + 1' shifts the pointer at the end of the array.
- The '*' returns the value of the variable located at '(&arr + 1)'.
- Now we subtract the original array 'arr' to get the length of the array.
Example
Here is an example implementing the above-mentioned steps to find the array size using pointer operators:
#include <iostream> using namespace std; int main() { int arr[5] = {5, 8, 1, 3, 6}; int len = *(&arr + 1) - arr; cout << "The length of the array is: " << len; return 0; }
Using size() Function
In the third approach to find the length of the array, we have used the size() function with array arr as an argument. This will return the size of the array. The size() function is supported in C++17 and above.
Example
Here is an example of implementing the above step for finding the length of the array using size() function:
#include <bits/stdc++.h> #include <iterator> using namespace std; int main() { int arr[5] = {4, 1, 8, 2, 9}; int count = size(arr); cout << "The length of the array is: " << count; return 0; }