C Program to calculate length of an array

In this tutorial, we will learn to write the C program to calculate the length of an array. There are multiple ways to write this program. In this tutorial, we will see two ways.

Programming logic to calculate the length of array

  • To calculate the length of array first we will find the size of a single element using sizeof() method.
  • Also using sizeof() method we can calculate the size of the array.
  • Now finally we will divide the array size with single element size to find the length of array.

C program to calculate the length of integer array

#include<stdio.h>
int main(){
	int len  =0;
	int arr[] = {2,4,6,8,9,4};//6 elements
	printf("C Program to calculate length of array(total Elements) \n");
	//sizeof(arr) in C calculate the total memory size
	printf("Size of Array is :%d \n",sizeof(arr));
	printf("Size of one int value is :%d \n",sizeof(int));
	//Here calculating length of array
	len  = sizeof(arr)/sizeof(int);
	printf("Length of Array is:%d",len);
	return 0;
}

Output

C Program to calculate length of an integer array

C program to calculate the length of char array

#include<stdio.h>
int main(){
	int len  =0;
	char arr[] = {'a','b','c','d','e'};//5 elements
	printf("C Program to calculate length of char array(total Elements) \n");
	//sizeof(arr) in C calculate the total memory size
	printf("Size of Array is :%d \n",sizeof(arr));
	printf("Size of one int value is :%d \n",sizeof(char));
	//Here calculating length of array
	len  = sizeof(arr)/sizeof(char);
	printf("Length of Array is:%d",len);
	return 0;
}

Output

C Program to calculate length of an char array