Write a C program to find the number of elements in an array.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int val1, val2, size, num;
/*
* fetching the address of first and
* second element in the given array
*/
val2 = (int)&arr[1];
val1 = (int)&arr[0];
/* size of an element in the given array */
size = val2 - val1;
/*
* number of elements equals total size of
* the array divided by size of an element
* in the given input array
*/
num = sizeof(arr) / size;
/* print the number of elements in the given array */
printf("Number of elements in the given array is %d\n", num);
return 0;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int val1, val2, size, num;
/*
* fetching the address of first and
* second element in the given array
*/
val2 = (int)&arr[1];
val1 = (int)&arr[0];
/* size of an element in the given array */
size = val2 - val1;
/*
* number of elements equals total size of
* the array divided by size of an element
* in the given input array
*/
num = sizeof(arr) / size;
/* print the number of elements in the given array */
printf("Number of elements in the given array is %d\n", num);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements in the given array is 5
Number of elements in the given array is 5
No comments:
Post a Comment