copying filtered array content to another array – Computer Sir Ki Class Code Learning #CPP#3102    ## copying filtered array content to another array

Demonstrating how to filter the array content and then copy it to another array.

## 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. On location that do not match the condition we fill some random out of range data.

## Source Code

 #include using namespace std; int main() { int ar={32,10,19,44,99}; int arf; for(int i=0;i<5;i++) if(ar[i]>30) arf[i]=ar[i]; else arf[i]=-1; for(int i=0;i<5;i++) if(arf[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; //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[i]=ar[i];
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.

else arf[i]=-1;
When filter is not met we try to fill the some data which is not likely to occur in our range. For example we filled -1 assuming the the range is all positive integer.

for(int i=0;i<5;i++) if(arf[i]>=0) cout<<arf[i]<<” “;
Here we print the data from the filtered array by checking for in range condition. In this example that condition was anything above -1 or >=0

## Notes

• In some condition we may not be able to decide regarding the value which would be out of range, as the entire range of data may be present in the input data array, in such cases we keep a separate value of count of filtered data and then while outputting the filtered data we use this count.

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

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

×