array element removal | Sololearn: Learn to code for FREE!

0

array element removal

void remove(float a[], int& n, int i); void read(float a[],int& n); void print(float a[],int& n); const int MAXSIZE=100; int main() { float a[MAXSIZE],element; int size; read(a,size); cout<<"the array is: "; print(a,size); cout<<"\nThe value you want to remove: "; cin>>element; remove(a,size,element); } void read(float a[],int& n) { n=0; do { cout<<"a["<<n<<"]="<<endl; cin>>a[n]; } while(a[n++]!=0 && n<MAXSIZE); --n; } void print(float a[],int& n) { for(int i=0; i<n; i++) { cout<<a[i]<<","; } } void remove(float a[], int& n, int i) { for (int j=i+1; j<n; j++) { a[j-1] = a[j]; --n; } } the code runs but after taking the array as input, the value I want to remove that part doesn't execute.What is the problem?

4/22/2021 8:40:54 PM

Ramisa Fariha

6 Answers

New Answer

+4

Note that your remove function does not delete the value specified. It removes the value at that index. In other words if you enter 5 it will delete the value found at a[5] not the array element that is equal to 5.0

+3

This is a terrible implementation since an array of MAXSIZE is always created. It is not possible to change the size of an array created this way. Using a list is a much better solution since the size of the list will grow and shrink as required. Your remove method is grocked. Move the --n statement outside of the loop void remove(float a[], int& n, int i) { for (int j=i+1; j<n; j++) { a[j-1] = a[j]; } --n; } otherwise you are decrementing n during every iteration.

+3

Input: 5 10 20 30 40 50 30 #include <iostream> using namespace std; void remove(float a[], int& n, int i); void read(float a[],int& n); void print(float a[],int& n); const int MAXSIZE=100; int main() { float a[MAXSIZE],element; int size; cin >> size; read(a,size); cout<<"the array is: "; print(a,size); cout<<"\nThe value you want to remove: "; cin>>element; cout<<element<<endl; remove(a,size,element) int new_size = size-1; print(a, new_size); } void read(float a[],int& n) { for(int i = 0; i < n; i++){ cout<<"a["<<i<<"]="<<endl; cin>>a[i]; } } void print(float a[],int& n) { for(int i=0; i<n; i++) cout<<a[i]<<","; } void remove(float a[], int& n, int i) { for (int j=0; j<n; j++) { if(a[j]==i){ for(int k=j; k<n-1; k++) a[k] = a[k+1]; break; } } }

+2

@Pieter Edwards The value of i is passed as an argument to the remove() function.

+1

I might be wrong but where did you declare I for the remove function? The only place I can see you have declared it is in a different function but variables don't transfer between functions That is probably your error because the for loop won't work

0

Thank you all very much for helping. I am just learning even though I don't like coding but I have to because I have this c++ course in this running semester.