While arrays in C have a fixed size, we can simulate inserting elements at different positions by shifting existing elements. Here's a program demonstrating insertion at the start, end, and in-between:
#include <stdio.h>
void insert_at_start(int arr[], int size, int new_value) {
// Check if array is full
if (size == 100) {
printf("Array is full!\n");
return;
}
// Shift elements to the right from the end
for (int i = size - 1; i >= 0; i--) {
arr[i + 1] = arr[i];
}
// Insert new value at the beginning
arr[0] = new_value;
// Increment array size
size++;
}
void insert_at_end(int arr[], int size, int new_value) {
// Check if array is full
if (size == 100) {
printf("Array is full!\n");
return;
}
// Insert new value at the end
arr[size] = new_value;
// Increment array size
size++;
}
void insert_at_index(int arr[], int size, int index, int new_value) {
// Check for invalid index
if (index < 0 || index > size) {
printf("Invalid index!\n");
return;
}
// Check if array is full
if (size == 100) {
printf("Array is full!\n");
return;
}
// Shift elements to the right from the given index
for (int i = size - 1; i >= index; i--) {
arr[i + 1] = arr[i];
}
// Insert new value at the given index
arr[index] = new_value;
// Increment array size
size++;
}
void print_array(int arr[], int size) {
printf("Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[100] = {1, 2, 3, 4, 5};
int size = 5;
// Insert at start
insert_at_start(arr, size, 0);
print_array(arr, size);
// Insert at end
insert_at_end(arr, size, 7);
print_array(arr, size);
// Insert inbetween (index 2)
insert_at_index(arr, size, 2, 6);
print_array(arr, size);
return 0;
}
This program defines three functions:
insert_at_start: Shifts existing elements and inserts at the beginning.
insert_at_end: Simply adds the element to the end of the array.
insert_at_index: Checks for invalid index and shifts existing elements before insertion at the specified index.
Remember that these functions modify the original array. Make sure to consider the array size limitations and handle invalid input accordingly.
Comments