Header Ads

WAP to Delete an Element at the given Position in an Array in C - 48

This Program Delete's an element in an Array, at any given position in an array in C.

Program Code:

/*  Program to delete an element at the given position in an array. */

#include <stdio.h>
#define MAX 256

int main() 
{
        int i, n, pos, array[MAX];

        /* get the number of elements from the input array */
        printf("\n Total Number of Elements in Array : ");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf(" Enter Array Elements : \n");
        for (i = 0; i < n; i++) {
                printf(" Array[%d] : ", i);
                scanf("%d", &array[i]);
        }

        /* get the position of the element to be deleted */
        printf(" Position of the Element to be Deleted : ");
        scanf("%d", &pos);

        if (pos < 1 || pos > n) {
                printf(" Error: Invalid Position!!\n");
                return 0;
        }

        /* reducing one from the total number of elements */
        n--;

        /* delete the element at the given position */
        for (i = pos - 1; i < n; i++) {
                array[i] = array[i + 1];
        }

        /* print the elements in the resultant array */
        printf(" Elements in Array Now is : \n");
        for (i = 0; i < n; i++) {
                printf(" Array[%d] : %d \n", i, array[i]);
        }

        printf("\n CodeGig.org \n\n");
 
        return 0;
  }

Program Output:

No comments