Engineers Gallery

Insert &Delete an element in 1-D array: C Program

C program to insert an element in 1-D array

This code will insert an element into an array, For example consider an array a[20] having three elements in it initially and a[0] = 6, a[1] = 7 and a[2] = 9 and you want to insert a number 10 at location 1 i.e. a[0] = 10, so we have to move elements one step below so after insertion a[1] = 6 which was a[0]=10 initially, and a[2] = 7 and a[3] = 9. Array insertion does not mean increasing its size i.e array will not be containing 21 elements.

[nextpage title="Program" ][message_box title="PROGRAM" color="yellow"]

#include <stdio.h>
#include <conio.h> 

void main()
{
   int array[20], position, c, n, value;
   clrscr();
 
   printf("Enter number of elements in array\n");
   scanf("%d", &n);
 
   printf("Enter %d elements\n", n);
 
   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);
 
   printf("Enter the location where you want to insert an element\n");
   scanf("%d", &position);
 
   printf("Enter the value to insert\n");
   scanf("%d", &value);
 
   for (c = n - 1; c >= position - 1; c--)
      array[c+1] = array[c];
 
   array[position-1] = value;
 
   printf("Resultant array is\n");
 
   for (c = 0; c <= n; c++)
      printf("%d\n", array[c]);
 
   getch();
}
[/message_box][/nextpage]
[nextpage title="OUTPUT" ][message_box title="OUTPUT" color="yellow"]
Enter number of elements in array
5
Enter 5 elements
3
5
6
7
9
Enter the location where you want to insert an element
3
Enter the value to insert
10

Resultant array is
3
5
10
6
7
9
[/message_box][/nextpage]

C  program to delete an element from  1-D array

This program delete an element from an array. Deleting an element does not affect the size of array. It is also checked whether deletion is possible or not, For example if array is containing five elements and you want to delete element at position six which is not possible.

[nextpage title=”PROGRAM” ][message_box title=”PROGRAM” color=”yellow”]

#include <stdio.h>
#include <conio.h> 
void main()
{
   int array[20], position, c, n;
   clrscr();
   printf("Enter number of elements in array\n");
   scanf("%d", &n);
 
   printf("Enter %d elements\n", n);
 
   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);
 
   printf("Enter the location where you wish to delete element\n");
   scanf("%d", &position);
 
   if ( position >= n+1 )
      printf("Deletion not possible.\n");
   else
   {
      for ( c = position - 1 ; c < n - 1 ; c++ )
         array[c] = array[c+1];
 
      printf("Resultant array is\n");
 
      for( c = 0 ; c < n - 1 ; c++ )
         printf("%d\n", array[c]);
   }
 
   getch();
}

[/message_box][/nextpage]

[nextpage title=”OUTPUT” ][message_box title=”OUTPUT” color=”yellow”]

Enter number of elements in array
5
Enter 5 elements
3
5
10
6
7
Enter the location where you want to delete an element
3
Resultant array is

3
5
6
7

[/message_box][/nextpage]

Exit mobile version