Sitemap

Data Structures and Algorithm_Arrays-3

Deletion from an Array

Simple explanation of Algorithm and C code on how to delete an item from an array.

1 min readSep 8, 2024

--

Algorithm —

DELETE (A ,N, K, ITEM)

Get Mohana Priya.T’s stories in your inbox

Join Medium for free to get updates from this writer.

Here, A is the array from where deletion takes place. N is the number of elements in the array. The deletion needs to occur from Kth location. ITEM is a variable which will contain the deleted item.

  1. Set ITEM = A[K]
  2. Repeat step 3 for I = K to N-1
  3. Set A[I] = A[I+1]
  4. Set N = N-1
  5. Exit

Explanation -

First place the item to be deleted into a variable called ITEM. This ensures its stored somewhere even after deletion. Now we need to move all the items after Kth place one step forward to occupy the empty space. This is done by the A[I] = A[I+1] step.

C Code -

// Deletion from Array
#include <stdio.h>
int main() {
char A[4] = {'W','O','R','D'};
printf("%c%c%c%c \n", A[0],A[1],A[2],A[3]);
// Delete letter R
int k = 2;
int n = 4;
int i = k;
char ITEM = A[k];
while ( i >= k && i <= n-1)
{
A[i] = A[i+1];
i++;
}
n--;
printf("%c%c%c \n", A[0],A[1],A[2]);
return 0;
}

--

--

Mohana Priya.T
Mohana Priya.T

Written by Mohana Priya.T

MP. T is a blogger, student and a perpetual day dreamer 😊 Check out her STEM blogs at https://mohanapriyawrites.wixsite.com/newtonsapple