How to Find Length of Array in C

How to Find the Length of the Array in C | To find the length of the array we have to use sizeof() function. The sizeof() function in C calculates the size in bytes of the passed variable or data type.

To calculate the length of the array, first, calculate the total size of the array and then calculate the size of the data type. After that divide the total size of the array/size of the data type.

Length of array = ( total size of array ) / ( size of data type )

int array[] = {10, 20, 30};
int size = sizeof(array) / sizeof(int);

The size of the data type is platform-dependent, therefore it is better to use the first element of the array.

Length of array = ( total size of array ) / ( size of first element of the array )

int array[] = {10, 20, 30};
int size = sizeof(array) / sizeof(array[0]);

Also see:- Quiz on sizeof() function in C

Let us demonstrate it through some examples,

#include <stdio.h>
int main()
{
  // variables
  int numbers[] = {10, 20, 30, 40, 50};

  // calculate size in bytes
  int arraySize = sizeof(numbers);
  int intSize = sizeof(numbers[0]);

  // length
  int length = arraySize / intSize;

  printf("ArraySize = %d bytes.\n", arraySize);
  printf("IntSize = %d bytes.\n", intSize);
  printf("Length of array = %d \n", length);
  return 0;
}

Output:-

ArraySize = 20 bytes.
IntSize = 4 bytes.
Length of array = 5

With the help of the length, we can iterate through the array. In the below C program first, we will find the length of the array and then display the array elements.

#include <stdio.h>
int main()
{
  // variables
  float arr[] = {10.5, 15.9, 25.2, 30.4, 55.59};

  // calculate length
  int length = sizeof(arr)/sizeof(arr[0]);
  printf("Array length = %d \n", length);

  // display the array
  printf("Array Elements are, \n");
  for (int i = 0; i < length; ++i)
  {
   printf("%.2f ", arr[i]);
  }
  return 0;
}

Output:-

Array length = 5
Array Elements are,
10.50 15.90 25.20 30.40 55.59

In the previous program, arr is the array of the floating-point data type. Now, let us see another C program to find the length of the char array.

#include <stdio.h>
int main()
{
  // variables
  char name[]={'K', 'n', 'o', 'w', 'P', 'r', 'o', 'g', 'r', 'a', 'm'};

  // calculate length
  int length = sizeof(name)/sizeof(name[0]);
  printf("Array length = %d \n", length);

  // display the array
  printf("Array Elements are, \n");
  for (int i = 0; i < length; ++i)
  {
   printf("%c", name[i]);
  }

  return 0;
}

Output:-

Array length = 11
Array Elements are,
KnowProgram

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply