Example 1 — Reverse, search, insert, delete
The array has capacity 10 and starts with 5 elements.
#include <stdio.h>
static void print(const int a[], int n) {
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
}
static void reverse(int a[], int n) {
for (int i = 0, j = n - 1; i < j; i++, j--) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
}
static int find(const int a[], int n, int key) {
for (int i = 0; i < n; i++) if (a[i] == key) return i;
return -1;
}
static int insert_at(int a[], int n, int pos, int v) {
for (int i = n; i > pos; i--) a[i] = a[i - 1];
a[pos] = v;
return n + 1;
}
static int delete_at(int a[], int n, int pos) {
for (int i = pos; i < n - 1; i++) a[i] = a[i + 1];
return n - 1;
}
int main(void) {
int a[10] = {1, 2, 3, 4, 5};
int n = 5;
reverse(a, n); print(a, n);
printf("index of 3: %d\n", find(a, n, 3));
n = insert_at(a, n, 1, 9); print(a, n);
n = delete_at(a, n, 0); print(a, n);
return 0;
} How It Works
reverseswaps from both ends until the pointers meet.findreturns the index or-1when missing.- Insert shifts elements right to open a gap; delete shifts left to close it.
- Both functions return the new length because the array itself does not track it.
