Skip to content

Instantly share code, notes, and snippets.

@itirkaa
Created July 17, 2019 18:40
Show Gist options
  • Save itirkaa/9c44021fff8bd368a520bd6010eefc90 to your computer and use it in GitHub Desktop.
Save itirkaa/9c44021fff8bd368a520bd6010eefc90 to your computer and use it in GitHub Desktop.
#include<iostream>
void printArray(int arr[], size_t size) {
// Function to print the array of size arr
for (int i = 0; i < size; i++) {
std::cout << arr[i] << std::endl;
}
}
int* insertElement(int arr[], size_t size, int ele, int index) { // Note: size is the size of argument arr[]
// Function to insert an element at given in index in an array
int* update_arr = new int[size + 1];
for (int i = 0; i < size; i++) {
if (i >= index) {
update_arr[index] = ele;
update_arr[i + 1] = arr[i];
}
else
update_arr[i] = arr[i];
}
return update_arr; // returns a new updated array
}
int main() {
size_t size;
std::cout << "Enter size of array: ";
std::cin >> size;
int* array = new int[size];
for (int i = 0; i < size; i++) {
std::cin >> array[i];
}
printArray(array, size);
int element, index;
std::cout << "Enter Element you want to insert and it's index: ";
std::cin >> element >> index;
int *update_array = insertElement(array, size, element, index);
printArray(update_array, size + 1);
delete[] array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment