copying filtered array content to another array by maintaining count – Computer Sir Ki Class

Code Learning #CPP#3106

copying filtered array content to another array by maintaining count

Demonstrating how to filter the array content and then copy it to another array by maintaining the filter size count.

Learning Objectives

• Getting specific data out from an array based on a condition called the filter condition and then filling this selected data into an destination array. In this case we maintain the destination array content count which can be used while taking out the filtered members.

Source Code

 #include using namespace std; int main() { int ar[5]={32,10,19,44,99}; int arf[5]; int cnt=0; for(int i=0,j=0;i<5;i++) if(ar[i]>30) { arf[j]=ar[i]; j++; cnt++; } for(int i=0;i=0) cout<

Run Output

``````32 44 99
``````

Code Understanding

int ar[]={32,10,19,44,99}; //An array with initialised integer values as the source array
int arf[5]; //This is the destination filtered array. It has to be the same size as it is possible that all members of the array are meeting the filter criterion

for(int i=0;i<5;i++)
loop to traverse the array terms one by one from index 0

if(ar[i]>30) {  arf[j]=ar[i]; j++; cnt++; }
With in if is the filter condition.  Once the condition is met here we are copying the data from original array to the destination array but with a separate index in the destination array. The destination array index moves only when the condition is met. If the condition is met we also increase a separate variable count so that keep a track over how much size filtered data has produced.

for(int i=0;i<cnt;i++) if(arf[i]>=0) cout<<arf[i]<<” “;
Here we print the data from the filtered array upto the count cnt maintained while filling. Beyond this count the destination array may contain any junk values.

Notes

• This program approach is useful to handle any data which can have any range of values.
• In modern programming approach we use pointer method or vector method to create dynamic arrays.

Suggested Filename(s): arr-filt-copy.cpp,arrfltcp.cpp

sunmitra| Created: 28-Jan-2018 | Updated: 28-Jan-2018|

×