In: Computer Science
************CODING IN C++ ONLY ********************
Instructions
Write a function, remove, that takes three parameters: an array of integers, the number of elements in the array, and an integer (say, removeItem).
The function should find and delete the first occurrence of removeItem in the array. (Note that after deleting the element, the number of elements in the array is reduced by 1.) Assume that the array is unsorted. Also, write a program to test the function.
Your program should prompt the user to enter 10 digits for the array. Display the starting array to the user and prompt them to select an integer to remove. After the selected integer has been removed, the updated list should be displayed to the user. If the value does not exist or the array is empty, output the following message: x is not in the list
GRADING CRITERIA
1) Defined the remove function
2) Removing elements from the list
3) List does not contain integer to be removed
TESTING WITH INPUT
2 7 6 8 3 9 10 1 5 4 6
OUTPUT SHOULD BE
2 7 8 3 9 10 1 5 4
*************************************
A SAMPLE OF MY CODE, IT HAS MANY ERRORS
#include <iostream>
using namespace std;
void remove(int arrayList[],int& size,int
removeItem)
{
int i, j;
for (i = 0; i < size; i++)
if (arrayList[i] == removeItem)
if(i == size-1)
{
//decrease items
size--;
return;
}
else
{
for (j = i; j < size-1; j++)
arrayList[j] = arrayList [j+1];
size --;
return;
}
cout <<" item" << remove item << is not found in
the array";
}
Below is the code
#include <bits/stdc++.h>
using namespace std;
void remove(int arr[],int size,int removeItem){
if(size==0){
cout<<"x is not in the list"<<endl;
return ;
}
else{
int flag = 0;
for(int i = 0;i<size;i++){
if(flag==1){
arr[i-1] = arr[i]; // shift the elements
}
if(removeItem==arr[i] and flag==0){ //check for if number exists or
not
flag = 1;
size--;
}
}
if(flag==1){
for(int i = 0;i<size;i++){
cout<<arr[i]<<" ";
}
}
else{
cout<<"x is not in the list"<<endl;
}
}
}
int main(){
cout<<"enter ten numbers"<<endl;
int arr[10];
for(int i =0;i<10;i++){
cin>>arr[i];
}
int size = 10;
cout<<"\narray before an element is
removed"<<endl;
for(int i = 0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<"\n Enter number to be removed"<<endl;
int removeItem;
cin>>removeItem;
remove(arr,size,removeItem);
}
2nd exmaple
if any doubt, comment below