C Online Compiler
Example: Array Insertion in C in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Array Insertion in C #include <stdio.h> #define MAX_SIZE 10 // Define a maximum physical size for the array // Function to print the array void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to insert an element at a specific position // Returns 1 on success, 0 on failure (e.g., array full or invalid position) int insertElement(int arr[], int *currentSize, int element, int position) { // Step 1: Check if the array is full if (*currentSize >= MAX_SIZE) { printf("Error: Array is full. Cannot insert.\n"); return 0; } // Step 2: Check for valid insertion position // Position must be between 0 and currentSize (inclusive) if (position < 0 || position > *currentSize) { printf("Error: Invalid position for insertion.\n"); return 0; } // Step 3: Shift elements to the right to make space // Start from the last element and move towards the insertion point for (int i = *currentSize - 1; i >= position; i--) { arr[i + 1] = arr[i]; } // Step 4: Insert the new element arr[position] = element; // Step 5: Increment the current size of the array (*currentSize)++; return 1; // Success } int main() { int arr[MAX_SIZE] = {10, 20, 30, 40, 50}; // Initial elements int currentSize = 5; // Current number of elements in the array printf("Original array: "); printArray(arr, currentSize); // Insert 25 at position 2 printf("Attempting to insert 25 at position 2...\n"); if (insertElement(arr, ¤tSize, 25, 2)) { printf("Array after insertion: "); printArray(arr, currentSize); } // Insert 5 at position 0 printf("Attempting to insert 5 at position 0...\n"); if (insertElement(arr, ¤tSize, 5, 0)) { printf("Array after insertion: "); printArray(arr, currentSize); } // Try to insert beyond max size (demonstrates error handling) printf("Attempting to insert 99 at an invalid position (large index)...\n"); insertElement(arr, ¤tSize, 99, 15); printf("Attempting to insert 60 at position 8 (array full scenario later)...\n"); if (insertElement(arr, ¤tSize, 60, currentSize)) { printf("Array after insertion: "); printArray(arr, currentSize); } printf("Current size after multiple insertions: %d\n", currentSize); return 0; }
Output
Clear
ADVERTISEMENTS