C Program to find the number of elements in an array
|In this C Programming example, we will implement the program to find the number of elements in an array and print the output on the console.
1. Number of elements in an array
To get the number of elements in an array we can calculate the length of an array by using the sizeof
operator which gives the size of an object or a type in bytes. So, to calculate the elements in the array we just divide the number of allocated bytes by the number of bytes of the array’s data type using sizeof()
.
Example Input: arr[]={1, 2, 3, 4, 5, 6, 7} Output: The number of elemnts present in the array are: 7
Helpful topics to understand this program better are-
2. C Program to find number of elements in an array
Let’s discuss the pseudocode for the program to find the number of elements in an array in C.
We will use sizeof()
method to find the size of the whole array and divide it by the size of the array’s first element.
Pseudocode Start Intialize arr[] # length_array = size of whole array / size of first item length_array = sizeof(arr) / sizeof(arr[0]) End
Let us now implement the above execution of the program to find the number of elements in an array in C.
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int arrayLength = sizeof(arr) / sizeof(arr[0]); printf("Number of elements present in the given array is: %d", arrayLength); return 0; }
Output Number of elements present in the given array is: 10
3. Conclusion
In this C Programming example, we have discussed how to find the number of elements in an array using the sizeof
operator.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?