Write and test the following function that attempts to remove an item from an array:
bool removeFirst(float a[],int& n,float x);
The function searches the first n elements of the array a for the item x. If x is found, its
firstoccurrence is removed, all the elements above that position are shifted down, n is decre-mented,
and true is returned to indicate a successful removal. If x is not found, the array is left unchanged and
false is returned.
1
Expert's answer
2015-07-01T06:53:28-0400
Answer
#include <iostream> using namespace std;
bool removeFirst(float a[],int& n,float x) { bool b=0; for (int i=0;i<n;i++) { if (a[i]==x) { for (int j=i;j<n;j++) { a[j]=a[j+1]; } n--; b=1; break; }
} return b; }
int main() { float ar[]={3,4,4,4,2,2,2,1}; int n=8; cout<<removeFirst(ar, n, 2)<<endl; for (int i=0;i<n;i++) cout<<ar[i]<<" "; }
Comments
Leave a comment