This blog is under construction

Thursday 25 July 2013

C program to delete an element at the given position in an array

Write a C 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("Number of elements in the input array:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array elements:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%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("Wrong 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 resultant array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", array[i]);
        }

        printf("\n");

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number of elements in the input array:5
  Enter your array elements:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40 
  Data[4]: 50
  Position of the element to be deleted:3
  Elements in resultant array:
  10 20 40 50 


No comments:

Post a Comment