Question #53186

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.

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.

Expert's answer

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]<<" ";

}

Output

1

3 4 4 4 2 2 1

#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]<<" ";

}

Output

1

3 4 4 4 2 2 1

## Comments

## Leave a comment