Delete an element from the array from user defined position.
Learn how to remove an element from any position in an array
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This header provides essential input/output functions:
printf()
for displaying outputscanf()
for reading user input- Other standard I/O operations
๐น Step 2: Declare Variables and Array
int arr[20], n, i, pos;
- arr[20]: Array with maximum capacity of 20 elements
- n: Current number of elements in the array
- pos: Position of element to be deleted
- i: Loop counter variable
๐น Step 3: Input Size and Elements of Array
printf("Enter number of elements (max 20): ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
- Gets the current size of the array (n ≤ 20)
- Collects each element from the user
- Stores elements sequentially in the array
๐น Step 4: Input Position to Delete
printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &pos);
- Gets the index of element to be removed
- Valid positions are between 0 and n-1
- Shows user the valid range in the prompt
๐น Step 5: Validate the Position
if(pos < 0 || pos >= n) {
printf("Invalid position!\n");
}
- Checks if position is negative
- Checks if position exceeds array bounds
- Provides error message for invalid input
๐น Step 6: Shift Elements to the Left
for(i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--;
- Starts from deletion position
- Moves each element one position left
- Overwrites the deleted element
- Decreases array size counter (n)
๐น Step 7: Display the Updated Array
for(i = 0; i < n; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
- Prints all elements after deletion
- Shows both index and value for each element
- Verifies the successful deletion
๐งช Sample Output
Enter number of elements (max 20): 5
Enter 5 elements:
arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50
Enter position to delete (0 to 4): 2
Array after deletion:
arr[0] = 10
arr[1] = 20
arr[2] = 40
arr[3] = 50
๐ Key Concepts Covered
Array Operations
Manipulating fixed-size collections of elements in memory
Element Deletion
Removing elements at specific positions by shifting elements
Left Shifting
Moving array elements to lower indices to fill deletion gap
Input Validation
Ensuring position is within valid bounds (0 to current size-1)
Size Management
Tracking and updating the current number of elements in the array
No comments:
Post a Comment