Get Number of Elements in Array in C++

Get Number of Elements in Array in C++

One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that we can use to access them. It holds the data in contiguous memory locations.

We will understand how to find the total number of elements of an array in this article.

Get Number of Elements in Array in C++

Using the sizeof() function

The sizeof() function in C++ returns the size of the variable during compile time. Arrays store elements of the same type. So, we can find out the total size of the array and divide it by the size of any element of the array to calculate its length.

We implement this in the following code.

Output:

Total number of elements in array is 8

Using the pointers

We can reference the memory location of objects using pointers. We can use the & sign to get the memory location of values. The * operator can declare pointers in C++ and dereference the values from these pointers. We will use these operators to create a logic, which will return the number of elements in an array.

Suppose we have an array called arr. Now, &arr+1 will point to the address of the element after the array. We can dereference it using the * operator and subtract the first element of the array to get its size.

See the code below.

Output:

Total number of elements in array is 8

Using the size() function

In C++ 17, a new size() function is present that can return the length of an array.

For example,

Output:

8

Get the frequency of each element in array in C++

We can also calculate the frequency of every element of the array in C++. There are two methods available for this.

Using nested for loop

We will iterate through every individual element and mark every element we visit in a new array in this approach. We will check if a match is found in the second loop, increment the count, and mark the element as visited.

This approach is tedious and time-consuming. The time complexity is O(n^2).

We will implement this in the following code.

Output:

10: 2
5: 2
8: 2
9: 3

In the above example,

  • We store the encountered element in the vis array.
  • If we have already encountered an element, we go to the next iteration using the continue statement.
  • If we have not encountered an element, we will check for it in the nested loop and find its total count by comparing it with every array element.

Using maps

A map stores key-value pairs in C++. We can iterate through the array and store every element and its count as a key-value pair. We will update the count in every iteration and display this map.

The time complexity is O(n).

For example,

Output:

5 : 2
8 : 2
9 : 3
10 : 2

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *