- 2071 Chaitra · 4 marks
Insert value in array at position
Short answer
If the array is not full and the position is valid, shift elements from the end down to that position one place right, insert the new value, and increment the element count.
Write an algorithm to insert a value in an array at a position given by user.
Algorithm: insert a value at a given position
Let A be the array with N elements (positions 1 to N), MAX the capacity, POS the position and VAL the new value.
- Start.
- Read N and the elements A[1] … A[N].
- Read POS and VAL.
- If N = MAX or POS < 1 or POS > N + 1, display "insertion not possible" and stop (overflow check).
- Set I = N.
- Repeat while I ≥ POS: set A[I + 1] = A[I]; set I = I − 1. (shift elements to the right)
- Set A[POS] = VAL.
- Set N = N + 1.
- Display A[1] … A[N].
- Stop.
Example: A = 10 20 30 40 50, POS = 3, VAL = 99. The elements 30, 40, 50 move one place right and 99 is stored at position 3, giving 10 20 99 30 40 50.
C implementation of the same algorithm:
#include <stdio.h>
int main(void)
{
int a[50], n, pos, val;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter position (1 to %d) and value: ", n + 1);
scanf("%d %d", &pos, &val);
if (n >= 50 || pos < 1 || pos > n + 1) {
printf("Insertion not possible\n");
return 1;
}
for (int i = n - 1; i >= pos - 1; i--) /* shift right */
a[i + 1] = a[i];
a[pos - 1] = val;
n++;
printf("New array: ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Output:
Input: 5 10 20 30 40 50 3 99
Enter number of elements: Enter elements: Enter position (1 to 6) and value: New array: 10 20 99 30 40 50
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Insert number at position in array · Computer Programming, chapter 11
- Insert a string into another string · Computer Programming, chapter 7
- Standard deviation and mean of array · Computer Programming, chapter 7
- Secant algorithm, versus false position · Numerical Method, chapter 2
- Insert and delete kth node in doubly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Insert before Kth node in doubly linked list · Data Structure and Algorithm, chapter 4
- Insert and delete before a node, singly linked · Data Structure and Algorithm, chapter 4