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.

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
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 Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.