Google Add

Search

C Program to Delete an Element from an Array

Write a c program to delete an element from an array at specified position. In this program, we take an input array and position to delete an array element from a user. Then we check whether a position entered by user is valid or not.

All elements of an array are stored in a contiguous memory location. To delete an element at index i in an array, We have to shift all elements from index i+1 to i to previous index.

For example - Take an array of length 5 and suppose we have to delete an element at index 3.

arr[] - {3, 8, 2, 7, 1}

position to delete an element : 3

 To delete an element, we have to move element at position 4 to 3 and position 5 to 4. Then we can decrement the size of an array.





Difference between array and linked list

C program to insert an element in an array


C Program to Delete an Element from an Array


C Program to Delete an Element from an Array


We have discussed how to delete an element from an array. Let's write a c code to delete an element from an array.

#include <stdio.h>

int main() {
    
    int arr[100], n, i, pos;
    
    printf("Enter the size of an array( Max 100) \n");
    scanf("%d", &n);
    
    printf("Enter an array elements \n");
    
    //Take input values
    
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    
    printf("Enter position to delete an element\n");
    scanf("%d", &pos);
    
    
    //Check valid delete positon
    
    if(pos < 0 || pos > n ) {
        printf("Invalid position");
        
    } else {
        
        //Traverse an array

        for(i = pos-1; i < n; i++) {

            arr[i] = arr[i+1];
        }

        //Decrement the size of an array
        n--;

        printf("Array after deleting an element\n");

        for(i = 0; i < n; i++) {

            printf("%d\n", arr[i]);
        }
    }
    
    return 0;
}



Output:

 Enter the size of an array 5

Enter an array elements


3
8
2
7
1

Enter position to delete an element 3

Array after deleting an element
3
8
7
1




  C++ program to delete an element from an array

Programming questions on array

C program to check Armstrong number


No comments:

Post a Comment