How to Count number of elements in array in C++

In this tutorial, we will learn how to count the number of elements in array in C++.

Array is a method of storing data together in C++. It has a fixed size so normally we do know the size of the array.
But, what if the user enters elements less than the size? How do we know how many elements are there in it?
Swipe down to find a solution to this problem

Count number of elements in array in C++

So what is an array? Array is a linear data structure that stores elements sequentially and has the capability to extract them using its Random Access property. Too many big words? Let’s simplify it.
1)Linear – Only one data element can be reached after the current element.
2)Random Access – Any element in the array can be accessed directly.

Array if not initialized gets stored with garbage value. And if this happens it’s almost impossible to count elements.

So let us see how to count the number of elements

Scenario 1: Pre-Entered Data Elements

Have a look at this code.

#include <iostream>
using namespace std;
int main()
{
    int arr[10] = {1,2,3,4};
    int count=0;
    for(int i=0;i<10;i++)
    {
        if(arr[i]!='\0')
            count++;
    }
    cout<<"Elements in array are: "<<count;
}

4 elements in the array are predefined by us. And the output We’re getting is:

Elements in array are: 4

So let’s break the code down:

1)Headers:

#include <iostream>
using namespace std;

We have “iostream” is used in this program for enabling input output
Also, “using namespace std;” is a shortcut to prevent you from writing “std::cout” every time you want to print something or “std::cin” every time you want to accept something

2)Initialising

int arr[10] = {1,2,3,4};
int count=0;

Here we are initializing the array of type int called “arr” with the size 10. As I said above, the array’s size is known to us.
We are placing 4 elements in this array: “1,2,3,4” all of type int cause the array’s type is int
The beauty of this is all the other elements in the array are automatically initialized to “\0” i.e. NULL

I am also initializing a variable “count” of type int to 0 to count the number of elements in the array

3)Counting And Displaying

for(int i=0;i<10;i++)
    {
        if(arr[i]!='\0')
            count++;
    }
cout<<"Elements in array are: "<<count;

So here we started a for loop from 0, that is the first index of the array, and it goes all the way up to 9, that is the last index of the array.
So basically we’re scanning every position in the array

We have put the if(arr[i]!=’\0′) there, to check whether the element is ‘\0’ or not. If it isn’t ‘\0’, it’ll increment the value of count by 1. Hence counting the elements in the array

This happens for every possible position in the array

Lastly, we are printing the number of elements in the array which is stored in “count”

 

Scenario 2: User Entered Elements

Have a look at the following code

#include <iostream>
using namespace std;
int main()
{
    int arr[10]={},count=0;;
    for(int i=0;i<4;i++)
    {
        cout<<"Enter an element:";
        cin>>arr[i];
    }
    for(int i=0;i<10;i++)
    {
        if(arr[i]!='\0')
            count++;
    }
    cout<<"Elements in array are: "<<count;
}

The output we’re getting is:

Enter an element:1                                                                                                                            
Enter an element:2                                                                                                                            
Enter an element:3                                                                                                                            
Enter an element:4                                                                                                                            
Elements in array are: 4

Now let’s see this line by line

  1. Headers
#include <iostream> 
using namespace std;

We have used the same headers as the previous scenario.
“iostream” for enabling input output
“using namespace std;” for preventing us from writing std::cout or std::cin every time

2) Initializing

int arr[10]={},count=0;

Again we’re initializing the same 2 variables as the previous scenario.
“arr[10]” is the array of type int with the size of 10 elements
“count” is used to count the number of elements in the array
You might have noticed the “{}” after the array is initialized. That initializes every position automatically to “\0”

3) Accepting elements

for(int i=0;i<4;i++)
    {
        cout<<"Enter an element:";
        cin>>arr[i];
    }

We’re currently only accepting 4 elements to keep the program simple but later on, when you’ll be coding with an unknown number of elements coming into the array you’ll be just replacing the “4 ” with the number of variables needed to be entered
So we ask the user for an element and store it in the i’th index of the array
i starts from 0 that is the first index and goes uptil 3

4) Counting and Displaying

for(int i=0;i<10;i++)
    {
        if(arr[i]!='\0')
            count++;
    }
cout<<"Elements in array are: "<<count;

Again, we’re doing a similar procedure as the previous scenario.
We are scanning every index’s value and if the value isn’t “\0”, we’re incrementing count by 1.
And lastly, we’re printing the number of non zero elements i.e. stored in count.

 

So basically the trick to find elements in an array is by initializing it to “\0”, and this works for int, char, float and string type of array.

And that is all. I hope you understood the logic and were able to execute it by yourself. If you have any doubts regarding this, feel free to ask it in the comment section. Thank You.

Leave a Reply

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