How to get the array size without null element in c++?

Member

by brock , in category: General Help , 2 months ago

How to get the array size without null element in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by monroe.bahringer , 2 months ago

@brock 

To get the array size without counting any null elements, you can iterate through the array and count the number of non-null elements. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>

int getArraySize(int arr[], int length){
    int count = 0;
    for(int i=0; i<length; i++){
        if(arr[i] != NULL) {
            count++;
        }
    }
    return count;
}

int main() {
    int arr[] = {1, 2, NULL, 4, NULL, 6};
    int length = sizeof(arr)/sizeof(arr[0]);
    
    int nonNullElements = getArraySize(arr, length);
    
    std::cout << "Array size without null elements: " << nonNullElements << std::endl;
    
    return 0;
}


Output:

1
Array size without null elements: 4


In this example, the getArraySize function takes the array (arr) and its length as parameters. In the function, we iterate through the array and increment the count variable whenever we encounter a non-null element. Finally, we return the count.


In the main function, we define the array (arr) and calculate its length using the sizeof operator. We then call the getArraySize function to get the count of non-null elements in the array and output the result.