C++ Program to Delete Element by Value

Write C++ Program to Delete Element by Value

// CPP Program to Delete Element by Value

#include <iostream>

using namespace std;

int main()
{
	int A[] = {1, 2, 6, 2, 7}, n, i, j, k, flag = 0;

	n = sizeof(A) / sizeof(A[0]);

	cout << "Array A :--> ";
	for(i=0; i<n; i++)
        cout << A[i] << " ";


	cout << "\nEnter Element to Delete :--> ";
	cin >> k;


	for(i = 0; i < n; i++)
	{
		if(A[i] == k)
		{
			flag = 1;
			int f;
			for(f = i; f < n-1; f++)
			   A[f] = A[f+1];
			n--;
		}
	}

	if(flag == 0)
	{
		cout << "\nElement Not Found";
	}
	else
	{
	    cout << "\nArray After Deleting Element :--> ";
		for(j = 0; j < n; j++)
		{
            cout << A[j] << " ";
		}
	}

	return 0;
}

Output:

Run 1:
Array A :--> 1  2  6  2  7
Enter Element to Delete :--> 2

Array After Deleting Element :--> 1  6  7


Run 2:
Array A :--> 1  2  6  2  7
Enter Element to Delete :--> 11

Element Not Found

≪ Previous | Next ≫