C Online Compiler
Example: Array Deletion in C in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Array Deletion in C #include <stdio.h> #define MAX_SIZE 10 // Define a maximum physical size for the array // Function to print the array (repeated for clarity, but ideally in a common utility) void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to delete an element from a specific position // Returns 1 on success, 0 on failure (e.g., array empty or invalid position) int deleteElement(int arr[], int *currentSize, int position) { // Step 1: Check if the array is empty if (*currentSize <= 0) { printf("Error: Array is empty. Cannot delete.\n"); return 0; } // Step 2: Check for valid deletion position // Position must be between 0 and currentSize - 1 (inclusive) if (position < 0 || position >= *currentSize) { printf("Error: Invalid position for deletion.\n"); return 0; } // Step 3: Shift elements to the left to overwrite the element at 'position' // Start from the element *after* the deletion point for (int i = position; i < *currentSize - 1; i++) { arr[i] = arr[i + 1]; } // Step 4: Decrement the current size of the array (*currentSize)--; return 1; // Success } int main() { int arr[MAX_SIZE] = {5, 10, 20, 25, 30, 40, 50, 60}; // Array after previous insertions int currentSize = 8; printf("Original array for deletion: "); printArray(arr, currentSize); // Delete element at position 2 (which is 20) printf("Attempting to delete element at position 2...\n"); if (deleteElement(arr, ¤tSize, 2)) { printf("Array after deletion: "); printArray(arr, currentSize); } // Delete element at position 0 (which is 5) printf("Attempting to delete element at position 0...\n"); if (deleteElement(arr, ¤tSize, 0)) { printf("Array after deletion: "); printArray(arr, currentSize); } // Delete element at the new last position (which is 60) printf("Attempting to delete element at last position (currentSize - 1)...\n"); if (deleteElement(arr, ¤tSize, currentSize - 1)) { printf("Array after deletion: "); printArray(arr, currentSize); } // Try to delete from an invalid position printf("Attempting to delete from an invalid position (large index)...\n"); deleteElement(arr, ¤tSize, currentSize); // currentSize is an invalid index printf("Current size after multiple deletions: %d\n", currentSize); return 0; }
Output
Clear
ADVERTISEMENTS