Calculate length of array in C – 2 Code Examples

Program to calculate length of array in C using sizeof operator with steps explained. Two program examples demonstrations using int array and char array.

Consider the example of an int array given below. The length of array is 6, in other word, number of elements in the int array is 6. This is what the c program will calculate.

int arr[] = {2,4,6,8,9,4};

LOGIC

  • Calculate the size of the array using sizeof operator e.g. sizeof(arr).
  • Calculate the size of an int value using sizeof(int).
  • To get the length of the array( number of elements), divide total size of array by size of 1 int.

Array length = size of array/ size of 1 int

NOTE: The size of data types varies with platforms. You can view here size of multiple data types in C with code example

Program to calculate length of array in C

/*
* C program to get length of int array
*/

#include<stdio.h>
int main(){

	int Length  =0;

	int arr[] = {2,4,6,8,9,4};//6 elements

	printf("Size of int array:%d \n",sizeof(arr));
	printf("Size of 1 int value :%d \n",sizeof(int));

	//Calculate length of the array ( Number of elements)
	Length  = sizeof(arr)/sizeof(int);

	//display array length

	printf("So, array length is:%d",Length );

	return 0;
}

Output:
Size of int array:24
Size of 1 int value :4
So, array length is:6

Lets see one more c program example to calculate length of char array.

Example of length of char array in C

In the below program there are 5 elements in the char array. When you divide it with a size of one char data type ( 1 byte), then the size of the array will be 5.

/*
* Example program to get length of char array in C
*/

#include<stdio.h>
int main(){

	int Length  =0;

	char arr[] = {'h','e','l','l','o'};//5 elements
	
	//Calculate length of the array ( Number of elements)
	Length  = sizeof(arr)/sizeof(char);

	//display array length
	printf("Char Array length is:%d",Length );

	return 0;
}

Output:
Char Array length is:5

Related Posts