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

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

#include<stdio.h>  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.

Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий