Home »
C programs »
C one-dimensional array programs
C program to count Array elements by using sizeof() operator
In this C program, we will learn how to count the total number of elements in a one dimensional array using sizeof() operator?
Submitted by IncludeHelp, on May 03, 2018
sizeof() operator returns the total number of size occupied by a variable, since array is also a variable, we can get the occupied size of array elements.
Logic
Get the occupied size of all array elements and divide it with the size of array type. Let suppose there is an integer array with 5 elements then size of the array will be 5*4=20 and the size of array type will be 4. Divide 20 by the 4 answer will be 5 which is the number of array elements.
Let's consider the following program
Program to count total number of array elements in C
#include <stdio.h>
int main()
{
int arr[]={10,20,30,40,50};
int n;
n=sizeof(arr)/sizeof(int);
printf("Number of elemenets are: %d\n",n);
return 0;
}
Output
Number of elemenets are: 5
Another method
We can divide the occupied size of all array elements by size of any one array element. Consider the following statement:
n=sizeof(arr)/sizeof(arr[0]);
C One-Dimensional Array Programs »