C program to find the Number of Elements in an Array-Length of an Array in C


Posted on 26 May 2017

Programming languages like Python, Java, PHP, JavaScript etc have predefined functions for finding the length of an array but when it comes to C there is no ready-made function for such operation so in this tutorial we will learn how to find the number of elements present in an array using C.

How to Calculate the number of elements in an Array

Recommended Read: Palindrome in C without using String.h functions

We are going to use a simple formula for this (total size of the array/size of an element of that array) for example there are 5 elements in an array of type integer then the total size of the array will be 10 bytes as each integer element takes 2 bytes of memory now if we divide the total size of 10 bytes with the size of an individual int element 10/2 then we get 5 which is the number of elements present in the array.

For finding the size of elements and datatypes we are going to use the sizeof operator of C.

Note: sizeof is not a function it is a unary operator which generates the size of a variable or datatype.

 C program to find the number of elements in an array


int main(){
	int a[] = {10,2,98,4,6,7};
	int len;
	len = (sizeof(a))/(sizeof(a[0]));;
	printf("The length of the array is: %d",len);
	return 0;

Output of the above code

lengthof an array in C

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts