Bird
0
0
DSA Cprogramming

Array Deletion at End in DSA C

Choose your learning style9 modes available
Mental Model
Removing the last item from a list means just ignoring it from now on.
Analogy: Think of a stack of plates where you only take the top plate off to remove it.
Index: 0   1   2   3   4
Array: 10 -> 20 -> 30 -> 40 -> 50
Size: 5
Dry Run Walkthrough
Input: array: [10, 20, 30, 40, 50], delete last element
Goal: Remove the last element and reduce the size by one
Step 1: Check if array is empty
10 -> 20 -> 30 -> 40 -> 50, size=5
Why: We must ensure there is something to delete
Step 2: Reduce size by 1 to remove last element
10 -> 20 -> 30 -> 40, size=4
Why: Reducing size ignores the last element effectively deleting it
Step 3: Print updated array
10 -> 20 -> 30 -> 40, size=4
Why: To confirm the last element is removed
Result:
10 -> 20 -> 30 -> 40 -> null
Annotated Code
DSA C
#include <stdio.h>

void deleteAtEnd(int arr[], int *size) {
    if (*size == 0) {
        printf("Array is empty, nothing to delete.\n");
        return;
    }
    (*size)--; // reduce size by 1 to delete last element
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d", arr[i]);
        if (i != size - 1) printf(" -> ");
    }
    printf(" -> null\n");
}

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int size = 5;

    deleteAtEnd(arr, &size);
    printArray(arr, size);

    return 0;
}
if (*size == 0) {
Check if array is empty to avoid deleting from empty array
(*size)--;
Reduce size by one to remove last element logically
for (int i = 0; i < size; i++) {
Traverse array up to current size to print elements
OutputSuccess
10 -> 20 -> 30 -> 40 -> null
Complexity Analysis
Time: O(1) because deleting last element just reduces size without shifting
Space: O(1) because no extra space is needed for deletion
vs Alternative: Compared to deleting from start or middle which requires shifting O(n), this is faster and simpler
Edge Cases
empty array
Prints message and does not change array
DSA C
if (*size == 0) {
array with one element
Size reduces to zero, array becomes empty
DSA C
(*size)--;
When to Use This Pattern
When you need to remove the last item quickly without rearranging others, use array deletion at end because it only changes size.
Common Mistakes
Mistake: Trying to shift elements after deleting last element
Fix: No shifting needed; just reduce size by one
Mistake: Not checking if array is empty before deletion
Fix: Add a check for size zero before deleting
Summary
Deletes the last element by reducing the array size by one.
Use when you want to remove the last item quickly without moving other elements.
The key is that reducing size ignores the last element without shifting.