Programming Examples

Cpp program to delete an element of an array


Write a cpp program to delete an element of an array using function

Solution

#include<iostream>
using namespace std;
int Lsrch(int [],int,int);
int main(){
    int arr[50],i,size,item,index;
    cout<<"Enter the desired size of array";
    cin>>size;
    cout<<"Enter the elements in the array";
    for(i=0;i<size;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the element that needs to be deleted: ";
    cin>>item;
    index=Lsrch(arr,size,item);
     //cout<<" Index is: "<< index;
    if(index==-1)
    {
        cout<<" Element cannot be found"<<endl;
    }
    else
    {
        cout<<"Element found at index "<<index<<",position "<<index+1<<endl;
    }
    for(i=index;i<size;i++)
    {
        arr[i]=arr[i+1];
    }
    size-=1;
    for(i=0;i<size;i++)
    {
        cout<<arr[i]<<" ";
    }
return 0;

}
int Lsrch(int arr[],int N,int ITEM)
{
    for(int i=0;i<N;i++)
    {
        if(arr[i]==ITEM)
        {
            return i;
        }
        
    }
    return -1;
}
Output

Enter the desired size of array 5

Enter the elements in the array

4

5

7

8

0

Enter the element that needs to be deleted: 8

Element found at index 3,position 4

4 5 7 0

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz