Certainly! In the context of computer science and programming, “insertion” in an array typically refers to the operation of adding an element into an array at a specific position. In C language, arrays are a collection of elements of the same data type stored in contiguous memory locations.
Example:
#include <stdio.h>
#define MAX_SIZE 100
void insertElement(int array[], int *size, int position, int element) {
// Check if the array is full
if (*size >= MAX_SIZE) {
printf(“Array is full. Insertion failed.\n”);
return;
}
// Shift elements to the right from the given position to make space for the new element
for (int i = *size; i > position; i–) {
array[i] = array[i – 1];
}
// Insert the element at the specified position
array[position] = element;
// Increment the size of the array
(*size)++;
printf(“Element inserted successfully.\n”);
}
int main() {
int arr[MAX_SIZE] = {1, 2, 3, 4, 5}; // Example array
int size = 5; // Current size of the array
int position, element;
printf(“Enter position to insert: “);
scanf(“%d”, &position);
printf(“Enter element to insert: “);
scanf(“%d”, &element);
// Call the insertElement function to insert the element
insertElement(arr, &size, position, element);
// Print the updated array
printf(“Updated Array:\n”);
for (int i = 0; i < size; i++) {
printf(“%d “, arr[i]);
}
printf(“\n”);
return 0;
}
In this code:
- We have a function
insertElementthat takes the array, its current size, the position where the element needs to be inserted, and the element to insert. - Inside
insertElement, we first check if the array is already full. If it is, we print a message indicating that insertion failed. - Then, we shift elements to the right starting from the given position to make space for the new element.
- After creating space, we insert the new element at the specified position.
- Finally, we update the size of the array and print a message indicating successful insertion.
- In the
mainfunction, we take input from the user for the position and element to be inserted, and then call theinsertElementfunction. - We print the updated array after insertion.