Home > Enterprise >  how to find the number of elements present in an array in C
how to find the number of elements present in an array in C

Time:09-22

suppose I have an array a[10] and it is filled up to 6 places example a[]={10,20,30,40,50,60} now rest 4 places are empty, now how do I print the number of places that are filled in an array-like in the above case it should print 6, given the scenario that I do not know the array beforehand like I do not have any clue what size it is or the elements that are there inside.

CodePudding user response:

int a[]={10,20,30,40,50,60} initilizes all 6 elements.

int b[10]={10,20,30,40,50,60} initilizes all 10 elements, the last ones to 0.

There is no partial initialization in C. There is no specified "empty".

to find the number of elements present in an array in C

size_t elemnt_count_a = sizeof a / sizeof a[0];  // 6
size_t elemnt_count_b = sizeof b / sizeof b[0];  // 10

I do not know the array beforehand

In C, when an array is defined, its size is known.

CodePudding user response:

if the array is a[]={10,20,30,40,50,60} here is my psedocode -

    int size = 0;
    if(i = 0; i < a.length(); i  ) {
        if(a[i] != null)
           size  
    }

the value of size should print 6

  • Related