Suppose we have an Array1 [5,3,8,15,12]. a) Function called Insert to add value at the beginning of Array. Now Array1 look like(if we insert 1 in beginning): [1,5,3,8,15,12]. b) Function called Insert to add value at the last of Array. Now Array1 look like(if we insert 17 in end): [5,3,8,15,12,17]. c) Function called remove to remove new value after specific value in list. Array1 is [5,3,8,15,12], if we remove 3 then it is [5,8,15,12]. d) Function called Display to show all values of Array1 [5,3,8,15,12]
#include <iostream>
using namespace std;
// Insert a value at the begining of the array
void insert_first(int arr[], int &n, int val) {
for (int i=n-1; i>=0; i--) {
arr[i+1] = arr[i];
}
arr[0] = val;
n++;
}
// Insert a value at the last of the array
void insert_last(int arr[], int &n, int val) {
arr[n++] = val;
}
// Remove a value from the array
bool remove(int arr[], int &n, int val) {
bool res = false;
int idx = -1;
for (int i=0; i<n; i++) {
if ( arr[i] == val) {
idx = i;
break;
}
}
if (idx >= 0) {
for (int i=idx+1; i<n; i++) {
arr[i-1] = arr[i];
}
res = true;
n--;
}
return res;
}
// Display te array
void display(int arr[], int n) {
cout << "[";
for (int i=0; i<n; i++) {
if (i>0) {
cout << ", ";
}
cout << arr[i];
}
cout << "]";
}
int main() {
int arr[10] = {5, 3, 8, 15, 12};
int n = 5;
cout << "Source array: ";
display(arr, n);
cout << endl;
insert_first(arr, n, 1);
cout << "After inserting first: ";
display(arr, n);
cout << endl;
insert_last(arr, n, 17);
cout << "After inserting last: ";
display(arr, n);
cout << endl;
remove(arr, n, 3);
cout << "After remove: ";
display(arr, n);
cout << endl;
return 0;
}
Comments
Leave a comment