Skip to main content

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.

  1. Start.
  2. Read N and the elements A[1] … A[N].
  3. Read POS and VAL.
  4. If N = MAX or POS < 1 or POS > N + 1, display "insertion not possible" and stop (overflow check).
  5. Set I = N.
  6. Repeat while I ≥ POS: set A[I + 1] = A[I]; set I = I − 1. (shift elements to the right)
  7. Set A[POS] = VAL.
  8. Set N = N + 1.
  9. Display A[1] … A[N].
  10. 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)

All Computer Programming chapter 7 questions →