C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs



Home » C programs » C One-D Array programs

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.
/*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.






You may also be interested in...

C/C++ Tips and Tricks...

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.


Comments and Discussions