Finding count of members in a linear array
Finding the number of members in an array using the sizeof operator
Learning Objectives
- A method to find the number of members present in an array.
Source Code
|
Run Output
Code Understanding
int a[]={1,2,3,4,5};
Here an integer array with 5 fixed members have been initialised
int cnt=sizeof(a)/sizeof(a[0]);
we first calculate the sizeof whole array which would be size of integer (4 or 2) multiplied by number of members. We then divide it by size of first member which is a[0]. As per rule an array has to be all same type of members so size of all members will be same. Thus this computation will give us the number of members in the array
cout<<“Count of members in given array = “<<cnt<<endl
Here we simple print the given count of members.
Notes
- This method of finding size of array can be used easily for any data type char, long, float, double etc. It can even be used of multi dimensional arrays.
Suggested Filename(s): arr-len.cpp, arr-memb-count.cpp
sunmitra| Created: 11-Jan-2018 | Updated: 11-Jan-2018|