In programming, arrays are a collection of elements of the same data type. It is often necessary to determine the length of an array to perform various operations on it.
In C++, we can use a function to find the length of an array. In this tutorial, we will learn how to find the length of an array in C++ using a function.
Steps:
1. Declare the array that you want to find the length of.
2. Write a function to find the length of the array.
3. Call the function and pass the array as a parameter.
4. Display the length of the array.
Here is the code to find the length of an array in C++ using a function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> using namespace std; int findLength(int arr[], int size){ int length = sizeof(arr)/sizeof(arr[0]); return length; } int main(){ int arr[] = {1,2,3,4,5}; int size = sizeof(arr)/sizeof(arr[0]); int length = findLength(arr, size); cout << "The length of the array is: " << length << endl; return 0; } |
Output:
The length of the array is: 2
Conclusion:
In this tutorial, we have learned how to find the length of an array in C++ using a function. We used the sizeof() function to determine the size of the array and divided by the size of the data type to get the length of the array.