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]);





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.