adplus-dvertising

C program to find the number of elements in an array

frame-decoration

C program to find the number of elements in an array

Problem Description

This C program finds the number of elements present in an array. This is simple program that depicts the number of elements of an predefined array.

C program to find the number of elements in an array - Source code
     
                
  /* C Program to Find the Number of Elements in an Array */

#include <stdio.h>

int main()
{
    int array[] = {5, 10, 35, 40, 50, 57, 100,150,180,7};
    int n,m;

    n = sizeof(array);
    m = n/sizeof(int);

    printf("Size of the given array is %d\n", m);
    return 0;
}
     
      

Program Output

Size of the given array is 10

Program Explanation

1. An int array is declared with any number of arbitrary elements.

2. The operator sezeof is used to find the length of array in bytes. To determine the number of elements in the array, we divided the total size of the array by the size of the type of element the array contains.

3. Here we have an integer array, so we divided the total size of array with the size of int. The size of int can vary from machine to machine.

4. If we have an character array or double array type, then we need to divide by the size of character and double type respectively.