Write a function, removeAt, that takes three parameters: an array of integers, t
ID: 3772387 • Letter: W
Question
Write a function, removeAt, that takes three parameters: an array of integers, the number of elements in the array, and an integer (say, index). The function should delete the array element indicated by index. If index is out of range or the array is empty, output an appropriate message. (Note that after deleting the element, the number of elements in the array is reduced by 1.) Assume that the array is unsorted. You can use the following code that creates the unsorted random array for you.
#include <iostream> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #define Size 1000 using namespace std; void initArray(int*); int main() { int i; int x[Size]; initArray(x); /* Your solution goes here */ } void initArray(int x[]) { int i,n; const int limit = 10000; n=Size; srand (time(NULL)); for(i=0;i<n;++i) x[i]=rand() % limit + 1; } void mySorting(int x[]) { /* Your solution Goes Here*/ }
Explanation / Answer
#include <iostream>
using namespace std;
void print (int [], int);
int removeAt(int [], int&, int);
int main()
{
int list[100] = {1, 2, 3, 6, 10, 14, 20, 25, 30, 40};
int listSize = 10, index;
print (list, listSize);
cout << "The Item to be removed indicated by the index: " ;
cin >> index;
removeAt(list, listSize, index);
print (list, listSize);
system ("PAUSE");
}
void print(int list[], int listSize)
{
for (int i = 0; i < listSize -1; i++)
{
cout << list[i] << ", ";
}
cout << list[listSize-1] << endl;
}
/* list[]=array, listlength=size of the array,index=index of the element to be deleted */
void removeAt(int list[], int& listLength, int index)
{
int j;
if (index < 0 || index > listLength - 1)
cout << "List is out of bound " << endl;
for(j = index; j < listLength -1; j++)
list[j] = list[j+1];
listLength--; /* deletes the array element indicated by index */
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.