Open In App

How to Check if an Array is Empty in C++?

In C++, arrays are fixed-size data structures that allow the users to store similar data in contiguous memory locations. In this article, we will learn how to check if an array is empty in C++.

Example:

Input:
arr[]={}
arr[]={1,2,3,4,5}

Output:
The array is empty
The array is not empty

Check if an Array is Empty

In C++, there is no direct way to check if array is empty or not. Arrays in C++ hold the assigned amount of memory and this memory will contain some garbage values even when we don't assign any valid value to the array elements. Also, there is no indicator that tells whether the given value is assigned by the user or it is a garbage value.

But we can have some methods to track the values count which can help in checking if the array is empty. One is maintaining a pointer that keep the track of the location of the last element present in the array. Other one is using a sentinal node to represent the end of the array.

The below example shows how the tracking of last element location helps in checking

C++ Program to Check if an Array is Empty

The below program illustrates how we can check if an array is empty or not in C++.

// C++ Program to illustrate how to check if an array is
// empty
#include <iostream>
using namespace std;

// Define a class named Array
class Array {
    int* arr; // Pointer to the first element of the array
    int* end; // Pointer to the last element of the array
    int capacity; // Size of the array

public:
    // Constructor that initializes the array, end pointer
    // and capacity
    Array(int size)
    {
        arr = new int[size];
        end = arr;
        capacity = size;
    }

    // Function to insert an element at the end of the array
    void insert(int val)
    {
        if (end - arr < capacity) {
            *end = val;
            end++;
        }
        else {
            cout << "Array is full.\n";
        }
    }

    // Function to check if the array is empty
    bool isEmpty() { return end == arr; }
};

int main()
{
    // Create an array of size 5
    Array a(5);

    // Check if the array is empty and print a message
    // accordingly
    if (a.isEmpty()) {
        cout << "Array is empty.\n";
    }
    else {
        cout << "Array is not empty.\n";
    }

    return 0;
}

Output
Array is empty.

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



Article Tags :