Find the number of element of array

In this C programming guide we will introduce you with a C program to find the number of element of array in C. Generally we define a array with its size inside square bracket like this,

int myArray[10]

But if we declare an array without its size like bellow;

int myArray[] = {2, 5, 8, 9};

Now, how can we calculate the size of this array. We will calculate using a logic here. This logic will equally work in any array of any data type. Let’s see the program bellow;

C program to find number of element of array

// find the number of element of array

#include <stdio.h>

int main(){

    int num_array[] = {4, 6, 4, 7, 8, 9, 3, 2};

    int arr_size;

    arr_size = sizeof(num_array) / sizeof(num_array[0]);

    printf("\nSize of array is = %d\n", arr_size);

    return 0;

}

Output of number of element program:

find-number-of-element-in-array-c-program-to-find-the-size-of-array

How the program calculates the size of array?

Here the array holds integer type data inside it. We know the size of integer data type is 4.

Now, the array size will be  4 * 8 = 32

Now, size of every element inside the array is 4.

As we know  32 / 4 = 8 and this program is using this logic to determine the size of this array.

#include <stdio.h>

int main(){

    int num_array[] = {4, 6, 4, 7, 8, 9, 3, 2};

    int arr_size;

    printf("Total size of array is = %d\n", sizeof(num_array));

    printf("Size of any element is = %d\n", sizeof(num_array[0]));

    printf("\nSo, array size will be %d / %d = %d\n",
            sizeof(num_array), sizeof(num_array[0]),
            sizeof(num_array)/sizeof(num_array[0]) );

    return 0;

}

Output :

Total size of array is = 32
Size of any element is = 4

So, array size will be 32 / 4 = 8

We can write the same code for any type of array although here we have used integer type array.

#include <stdio.h>

int main(){

    char char_array[] = {'p', 'q', 'r', 's', 't', 'u', 'v', 'w'};

    int arr_size;

    arr_size = sizeof(char_array) / sizeof(char_array[0]);

    printf("\nSize of array is = %d\n", arr_size);

    return 0;

}

Compile and run this program which will give you the number of element of the array like this.

Size of array is = 8

Previous pageSum of array element

Next pageMerge two array