Count the number of null elements in an array in C++

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

There is no predefined string data type in C because of which in order to create a string we have to use a character array.

So to make an array of strings, we have to make use of a 2-dimensional array(matrix) where each row holds different strings in that matrix.

C++ overcomes this drawback of C language because of a predefined class called “string” in C++. Using this string class, we can create objects to store string data types and use them very efficiently. (Note:- String is not a primary data type.)

Null elements are those elements of a string array that do not contain any character within the double-quotes. For eg,

#include<iostream>
#include<string.h>

using namespace std;

int main()
{
string s[] = {"There is a null element","after","this",""};

return 0;
}

Here the last element of the array ‘s’ i.e. s[3] is a null element as it contains no characters within the double-quotes.

Counting Null Elements using C++ for loop

The basic approach is to access each element of string from start to end. Increment a pre-initialized counter by ‘1’ whenever a null element is encountered.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  int count = 0;    // Counter initialized to zero
  string s1[7] = {"India","is","","my","","","country"}; // Defined a string array 's1' of size 7

  for(int i=0; i<7; i++)
  {
    if(s1[i]=="")
      count++;   // Whenever a null element is encountered increment the counter
  }

  cout<<"Number of null elements in s1 are: "<<count; // Output the counter value on the screen

    return 0;
}

The output for the above program is,

Number of null elements in s1 are: 3

Comment for any queries.

Thank You!

Leave a Reply

Your email address will not be published.