how to delete integers from an array
Apr 6, 2009 at 8:39pm UTC
The function should remove all the occurrences of an integer (say, removeItem) from an array. If the value does not exist or the array is empty, ,output an appropriate message.
My program is able to print the array without all the occurences of removeItem , but I don't know how to output appropriate message if the value doesn't exist or the array is empty. Any help will be greatly appreciated .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include<iostream>
using namespace std;
const int ARRAY_SIZE = 10;
void removeAll(int list[], int ARRAY_SIZE, int removeItem);
int main()
{
int list[ARRAY_SIZE];
int index, removeItem;
cout << "Enter " << ARRAY_SIZE << " integers:" << endl;
for (index= 0; index < ARRAY_SIZE; index++)
cin >> list[index];
cin.ignore(100, '\n' );
cout << "Enter the number to be removed: " << endl;
cin >> removeItem;
cout << "After removing " << removeItem
<< " the list is: " << endl;
removeAll(list, ARRAY_SIZE, removeItem);
cout << endl;
system("PAUSE" );
return 0;
}
void removeAll(int list[], int ARRAY_SIZE, int removeItem)
{
int loc;
for (loc = 0; loc < ARRAY_SIZE; loc++)
if (list[loc] != removeItem)
cout << list[loc] << " " ;
}
Apr 6, 2009 at 9:05pm UTC
I would just create a variable "count" that counts how many times you removed the specific instance. Then you can just check whether it is 0 or not.
Apr 6, 2009 at 9:53pm UTC
Thanks firedraco, your suggestion is very helpful.
Here is my ipdated program which works fine now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include<iostream>
using namespace std;
const int ARRAY_SIZE = 10;
int removeAll(int list[], int ARRAY_SIZE, int removeItem);
int main()
{
int list[ARRAY_SIZE];
int counter, index, removeItem;
cout << "Enter " << ARRAY_SIZE << " integers:" << endl;
for (index= 0; index < ARRAY_SIZE; index++)
cin >> list[index];
cin.ignore(100, '\n' );
cout << "Enter the number to be removed: " << endl;
cin >> removeItem;
counter = removeAll(list, ARRAY_SIZE, removeItem);
if (counter == 0)
cout << "The number " << removeItem << " is not in the list. " << endl;
else
{
cout << "After removing " << removeItem
<< " the list is: " << endl;
for (index = 0; index < ARRAY_SIZE; index++)
{
if (list[index] != removeItem)
cout << list[index] << " " ;
}
}
cout << endl;
system("PAUSE" );
return 0;
}
int removeAll(int list[], int ARRAY_SIZE, int removeItem)
{
int counter = 0;
int loc;
for (loc = 0; loc < ARRAY_SIZE; loc++)
if (list[loc] == removeItem)
counter++;
return counter;
}
Topic archived. No new replies allowed.