C program to delete an array element using Pointers


Problem

Write a C program to delete an element from an array at runtime by the user and the result to be displayed on the screen after deletion. If the deleted element is not in an array, then we need to display Invalid Input.

Solution

An array is used to hold the group of common elements under one name.

The array operations are as follows −

  • Insert
  • Delete
  • Search

Algorithm

Refer an algorithm to delete the elements into an array with the help of pointers.

Step 1 − Declare and read the number of elements.

Step 2 − Declare and read the array size at runtime.

Step 3 − Input the array elements.

Step 4 − Declare a pointer variable.

Step 5 − Allocate the memory dynamically at runtime.

Step 6 − Enter an element that to be deleted.

Step 7 − After deletion, the elements are shifted to left by one position.

Example

Size of array is: 5

The array elements are as follows −

1 2 3 4 5

Enter the position the element that to be deleted: 4

The output is as follows −

After deletion the array elements are:
1 2 3 5

Example

Following is the C program to insert the elements into an array with the help of pointers −

 Live Demo

#include<stdio.h>
#include<stdlib.h>
void delete(int n,int *a,int pos);
int main(){
   int *a,n,i,pos;
   printf("enter the size of array:");
   scanf("%d",&n);
   a=(int*)malloc(sizeof(int)*n);
   printf("enter the elements:
");    for(i=0;i<n;i++){       scanf("%d",(a+i));    }    printf("enter the position of element to be deleted:");    scanf("%d",&pos);    delete(n,a,pos);    return 0; } void delete(int n,int *a,int pos){    int i,j;    if(pos<=n){       for(i=pos-1;i<n;i++){          j=i+1;          *(a+i)=*(a+j);       }       printf("after deletion the array elements is:
");       for(i=0;i<n-1;i++){          printf("%d
",(*(a+i)));       }    }    else{       printf("Invalid Input");    } }

Output

When the above program is executed, it produces the following output −

enter the size of array:5
enter the elements:
12
34
56
67
78
enter the position of element to be deleted:4
After deletion the array elements are:
12
34
56
78

Updated on: 26-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements