find length of array c++

Finding the Length of an Array in C++

To find the length of an array in C++, you can use the sizeof operator. Here are the steps to do this:

  1. Declare the Array: Declare the array for which you want to find the length.

  2. Calculate the Length: Use the sizeof operator to calculate the length of the array in bytes. Then, divide the total size of the array by the size of a single element to get the number of elements in the array.

Here's an example of how to find the length of an array in C++:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int length = sizeof(arr) / sizeof(arr[0]);

    cout << "The length of the array is: " << length << endl;

    return 0;
}

In this example, the sizeof(arr) returns the total size of the array in bytes, and sizeof(arr[0]) returns the size of the first element in the array. Dividing the total size of the array by the size of a single element gives the number of elements in the array, which is the length of the array.