Q:

C program to delete given element from one dimensional array

0

C program to delete given element from one dimensional array

Given an array with N integer elements and we have to delete given element from the array using C program.

Example:

    Input array elements:
    10, 10, 20, 30, 10
    Enter element to delete: 10

    Output:
    Sorted array elements:
    10 found 3 times and deleted successfully.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

/* C program to delete given element from 
one dimensional array. */

#include <stdio.h>
#define MAX 100

int main()
{
    int arr[MAX], n, i, j;
    int num, countDel;

    printf("Enter total number of elements: ");
    scanf("%d", &n);

    //read array elements
    printf("Enter array elements:\n");
    for (i = 0; i < n; i++) {
        printf("Enter element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }

    printf("\nEnter number (element) to delete: ");
    scanf("%d", &num);

    //delete elements
    countDel = 0;
    for (i = 0; i < n; i++) {
        if (arr[i] == num) {
            countDel++;
            //shift all other elements up
            for (j = i; j < n; j++) {
                arr[j] = arr[j + 1];
            }
        }
    }
    if (countDel)
        printf("%d found %d times and deleted successfully.", num, countDel);
    else
        printf("%d not found.", num);

    printf("\nArray elements after deleting %d.\n", num);
    for (i = 0; i < (n - countDel); i++) {
        printf("%d\n", arr[i]);
    }
    return 0;
}

Output:

    First Run:
    Enter total number of elements: 10
    Enter array elements:
    Enter element 1: 10
    Enter element 2: 20
    Enter element 3: 10
    Enter element 4: 30
    Enter element 5: 10
    Enter element 6: 40
    Enter element 7: 10
    Enter element 8: 50
    Enter element 9: 60
    Enter element 10: 70

    Enter number (element) to delete: 10
    10 found 4 times and deleted successfully.

    Array elements after deleting 10.
    20
    30
    40
    50
    60
    70

    Second Run:
    Enter total number of elements: 10
    Enter array elements:
    Enter element 1: 10
    Enter element 2: 20
    Enter element 3: 10
    Enter element 4: 30
    Enter element 5: 10
    Enter element 6: 40
    Enter element 7: 10
    Enter element 8: 50
    Enter element 9: 60
    Enter element 10: 70

    Enter number (element) to delete: 90
    90 not found.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the first repeated element in an... >>
<< C program to sort a one dimensional array in desce...