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

    // Heading for the program
    printf("=== C Program to Calculate Length of Array (Total Elements) ===\n");

    // sizeof(arr) in C calculates the total memory size
    printf("Size of array is: %ld bytes\n", sizeof(arr)); // Use %ld for long unsigned int
    printf("Size of one int value is: %ld bytes\n", sizeof(int)); // Use %ld for long unsigned int

    // Here, calculating the length of the array
    len = sizeof(arr) / sizeof(int);
    printf("Length of array is: %d\n", len);

    return 0;
}

Output

=== C Program to Calculate Length of Array (Total Elements) ===
Size of array is: 24 bytes
Size of one int value is: 4 bytes
Length of array is: 6

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

    // Heading for the program
    printf("=== C Program to Calculate Length of Char Array (Total Elements) ===\n");

    // sizeof(arr) in C calculates the total memory size
    printf("Size of array is: %ld bytes\n", sizeof(arr)); // Use %ld for long unsigned int
    printf("Size of one char value is: %ld bytes\n", sizeof(char)); // Use %ld for long unsigned int

    // Here, calculating the length of the array
    len = sizeof(arr) / sizeof(char);
    printf("Length of Array is: %d\n", len);

    return 0;
}

Output

=== C Program to Calculate Length of Char Array (Total Elements) ===
Size of array is: 5 bytes
Size of one char value is: 1 bytes
Length of Array is: 5
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now