Insert an element into the array at user defined position.
Learn how to insert an element at 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, value;
- arr[20]: Array with maximum capacity of 20 elements
- n: Current number of elements in the array
- pos: Position where new element will be inserted
- value: The element to be inserted
- i: Loop counter variable
๐น Step 3: Input Array Elements
printf("Enter number of elements (max 19): ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
- First gets the current size of the array (n)
- Then collects each element from the user
- Stores elements sequentially in the array
- Limits to 19 elements to leave space for insertion
๐น Step 4: Input Position and Value to Insert
printf("Enter the element to insert: ");
scanf("%d", &value);
printf("Enter the position (0 to %d): ", n);
scanf("%d", &pos);
- Gets the new value to be inserted
- Gets the insertion position (0 to n)
- Valid positions are between 0 and current size (n)
๐น Step 5: Shift Elements to the Right
for(i = n; i > pos; i--) {
arr[i] = arr[i - 1];
}
- Starts from the end of the array
- Moves each element one position to the right
- Creates space at the insertion point
- Works backwards to avoid overwriting data
๐น Step 6: Insert the New Value
arr[pos] = value;
n++;
- Places the new value at the specified position
- Increments the array size counter (n)
- Maintains array integrity
๐น Step 7: Display the Updated Array
for(i = 0; i < n; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
- Prints all elements including the new insertion
- Shows both index and value for each element
- Verifies the successful insertion
๐งช Sample Output
Enter number of elements (max 19): 5
Enter 5 elements:
arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50
Enter the element to insert: 99
Enter the position (0 to 5): 2
Array after insertion:
arr[0] = 10
arr[1] = 20
arr[2] = 99
arr[3] = 30
arr[4] = 40
arr[5] = 50
๐ Key Concepts Covered
Array Operations
Manipulating fixed-size collections of elements in memory
Element Insertion
Adding new elements at specific positions by shifting existing elements
Right Shifting
Moving array elements to higher indices to create space for insertion
Position Validation
Ensuring insertion position is within valid bounds (0 to current size)
Size Management
Tracking and updating the current number of elements in the array
No comments:
Post a Comment