Lesson 6 of 8 · Functions and Arrays · 3 min read · Updated

Array positions: insert, delete and search

Working with index positions: putting a value in the middle, removing one, and finding where a value is.

Every element has a position number — its index — starting from 0.

In C an array has a fixed capacity (how many boxes exist) and you keep a separate count of how many are in use. Inserting or deleting in the middle means shifting the other elements along — C has no built-in function for it.

c
#include <stdio.h>

void print(int a[], int n)
{
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

int main(void)
{
    int a[10] = {10, 20, 30, 40, 50};   /* capacity 10 */
    int n = 5;                          /* in use: 5 */

    /* Insert 25 at position 2: shift right, starting from the end */
    int pos = 2, value = 25;
    for (int i = n; i > pos; i--) {
        a[i] = a[i - 1];
    }
    a[pos] = value;
    n++;
    print(a, n);

    /* Delete position 0: shift left */
    for (int i = 0; i < n - 1; i++) {
        a[i] = a[i + 1];
    }
    n--;
    print(a, n);

    /* Search: find the position of 40 */
    for (int i = 0; i < n; i++) {
        if (a[i] == 40) {
            printf("40 is at position %d\n", i);
            break;
        }
    }
    return 0;
}
Output
10 20 25 30 40 50
20 25 30 40 50
40 is at position 3
  • Insert: shift from the end backwards, so nothing is overwritten before it is moved; then place the value and add 1 to the count.
  • Delete: shift everything after the position one place left; then subtract 1 from the count.
  • Search: walk the positions from 0 and stop at the first match; if the loop ends, it is not there.

Warning

"Position 2" in C means the third element, because counting starts at 0. When a user says "the 3rd element", subtract 1 to get the index. And before inserting, check n is less than the capacity — writing past the end is not caught by C.

To insert into position 1 of {5, 6, 7}, which element moves first?

Try this now

  1. Turn insert, delete and search into three functions and build a small menu around them.
  2. Count how many times a value appears in an array, and print every position where it appears.
  3. Reverse an array in place by swapping position i with position n − 1 − i.

Create a free account to save your progress, or sign in.