I have an array variable, say for an example:-
int a[10];
And suppose i have added 4 elements say 1,2,3,4 starting from a[0] till a[3].
Now how do i find that how much element is present in the array variable a whose max size is 10?
My way to obtain the number of elements present in the array assuming that user will give input greater than or equal to Zero:-
#include<iostream>
using namespace std;
#define SIZE 10
int main(){
int *a = (int*)malloc(sizeof(int)*SIZE);
int iCount=0;
int iNumberOfElements,iElements;
cout<<"\nEnter the number of elements to be entered:";
cin>>iNumberOfElements;
cout<<"\nEnter the elements(Please enter elements greater than or equal to zero):\n";
for (int jIndex = 0; jIndex < iNumberOfElements; jIndex++){
cin>>iElements;
while(iElements<0){
cout<<"\nPlease enter the element greater than or equal to Zero.\nRe-enter:\n";
cin>>iElements;
}
a[jIndex] = iElements;
}
for(int iIndex=0;iIndex<SIZE;iIndex++){
if(a[iIndex] >= 0){ //I am checking in this way assuming that user will give input >= 0
iCount++;
}
}
cout<<"\nThe total number of element present in the array is:"<<iCount<<endl;
return 0;
}
You have to build in that convention yourself.
For instance, you could initialize the whole array to some magic constant that signals “not in use”, or you could track the length through a separate variable.
Either way, the framework will not help you at all, there is no way. For all intents and purposes, the array has 10 elements, whether you set them or not.