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.





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.