How to Get the length of an Array in C

array logo

Array in C

an array is a collection of a variable of a fixed number of the same data type in a sequential memory.

an array can be declared in various ways. one of them is given below

int x[] = {200,300,522,655};
char y[] = {'x','s','r'};
int n[10],j; // first declaring the array
// then assigning the value.
for ( j = 0; j < 10; j++ ) {
n[ j ] = j + 100;
}

indexing in C array starts from the 0.

so if you want to access the 4th element then you have to use x[3].
that's enough intro about the array.

Getting Length of the Array in C

to get the length of the array first we divide the size of the full array by the size of the one element of the array.

Please note there is another way of getting the length of the char array (you can use strlen).

you can see this in the given program.

#include <stdio.h>

int main(){
int x[] = {200,300,522,655};
char y[] = {'x','s','r'};
// determining the size of the array
// getting the size of the full array
size_t n = sizeof(x);
// getting the size of the one element
// which can be a float or the char or int.
size_t i = sizeof(x[0]); // size of the integer is 4 bytes
int arrayLen = 0;
arrayLen = n/i;
printf("Length of the integer array is %d\n",arrayLen );

n = sizeof(y);
i = sizeof(y[0]); // size of the char is 1 byte in my machine
arrayLen = n/i;
printf("Length of the Character array is %d\n",arrayLen );
return 0;
}

The output of this program is
Output of the array length

If you have liked this post then you can check out the similar post below.

If any Query or suggestion then write them in the comment section.

Comments

Popular posts from this blog

C/C++ program to check the Palindrome string.

Second Equation of motion, How to implement using C language

Third Equation of motion, How to implement using C language