0% found this document useful (0 votes)
6 views4 pages

Practical Number 2 - 102623

Uploaded by

17.vikashverma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Practical Number 2 - 102623

Uploaded by

17.vikashverma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Practical Number: 2

Write a program to delete an element from a given whose value is given or


position is given.
Sol: To delete element from array we need to find for key element which we have
to delete for that iterate over the array and as we found the key element in array
shift elements to its previous index.
#include<iostream>
using namespace std;

void deleteByEle(int arr[], int n, int ele){


bool found = false;
for(int i=0; i<n; i++){
if(arr[i] == ele){
found = true;
}
if(found){
arr[i]= arr[i+1];
}
}
}

void deleteByPos(int arr[], int n, int pos){


bool found = false;
for(int i=0; i<n; i++){
if(i == pos){
found = true;
}

if(found){
arr[i]= arr[i+1];
}
}
}

int main(){
int n;
cout<<"Enter number of element in array : ";
cin>>n;

int arr[n];
cout<<"Enter elements in array : ";
for(int i=0; i<n; i++){
cin>>arr[i];
}

int pos,ele,op;
cout<<"Press 1 to delete element on the basis of postion and Press 2 to delete
on the basis of element "<<endl;
cin>>op;
if(op == 1){
cout<<"Enter postion : ";
cin>>pos;
deleteByPos(arr,n,pos);
}
else{
cout<<"Enter element : ";
cin>>ele;
deleteByEle(arr,n,ele);
}

cout<<"Resultant array : ";


for(int i=0; i<n-1; i++){
cout<<arr[i]<<" ";
}
return 0;
}
Output:

You might also like