Open In App

How to Find the Length of an Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. The length of an array is defined as the total number of elements present in the array. In this article, we will learn how to find the length of an array in C++.

Example:

Input: 
arr[]= {10, 20, 30, 40, 50}

Output:
Length of the array is 5

Find Array Length in C++

To find the array length in C++, we can use the sizeof that returns the size of the datatype or variable passed as argument. We first calculate the size of the array in bytes and then the size of the first element, and then divide both the values to get the length of the array.

Syntax of sizeof() in C++

sizeof(arr)/sizeof(arr[0])

Note: We cannot find the size of those array that are passed to the functions. See this article for details – Array Decay in C++

C++ Program to Find Array Length

C++
// C++ Program to illustrate how to find the length of an
// array
#include <iostream>
using namespace std;

// Driver code
int main()
{
    // Initializing an arraay with some elements
    int arr[] = { 1, 2, 3, 5, 6, 7, 8, 9 };
    // Finding the length of the array
    int length = sizeof(arr) / sizeof(arr[0]);
    // Printing the length of the array
    cout << "Length of the array is " << length << endl;

    return 0;
}

Output
Length of the array is 8

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads