C Program to Find the Number of Elements in an Array

«
»

This is a C Program to find the number of elements in an array.

Problem Description

This C Program finds the number of elements present in the given array.

Problem Solution

1. Create an array along with the definition of all its elements.
2. Create a variable which will hold the size of the array.
3. Using the inbuilt function sizeof(), passing the name of the array whose size we need to calculate, returns the number of elements contained by array.
4. The returned value is stored in the variable created above.

advertisement
Program/Source Code

Here is source code of the C Program to find number of elements present in the given array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1.  
  2.     /*
  3.      * C Program to Find the Number of Elements in an Array
  4.      */
  5.  
  6.     #include <stdio.h>
  7.     #include <stdlib.h>
  8.     #include <unistd.h>
  9.  
  10.     int main()
  11.     {
  12.         int array[] = {15, 50, 34, 20, 10, 79, 100};
  13.         int n; 
  14.         n = sizeof(array);
  15.         printf("Size of the given array is %d\n", n/sizeof(int));
  16.         return 0;
  17.     }
Program Explanation

1. Declare an array and define its elements at the time of declaration.
2. Create a variable n, which will store the size of the array, i.e total number of elements present in array.
3. Now, call an inbuilt function sizeof() (from unistd.h library) passing the name of the array as its parameter.
4. This function will return the number of elements present in the array passed to it.
5. Store it in variable n.

advertisement
Runtime Test Cases
Size of the given array is 7

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn