Computer Science, asked by ashkavishwakarma, 3 months ago

create an array 'a1' with 'n' elements. insert an element in ith position of 'a1' and also delete an element from jth position of 'a1'​

Answers

Answered by dreamrob
0

Program in C++

#include<iostream>

using namespace std;

void display(int a[] , int n)

{

for(int i = 0 ; i < n ; i++)

{

 cout<<a[i]<<"\t";

}

}

int main()

{

int n , a1[100] , i , j;

cout<<"Enter number of elements : ";

cin>>n;

cout<<"Enter elements in array : "<<endl;

for(int i = 0 ; i < n ; i++)

{

 cin>>a1[i];

}

cout<<"Array : ";

display(a1 , n);

cout<<"\n\nEnter position (form 1 to "<<n<<") at which you want to insert the element : ";

cin>>i;

if(i > n)

{

 cout<<"Invalid position";

}

else

{

 for(int x = n-1 ; x >= i-1 ; x--)

 {

  a1[x+1] = a1[x];

 }

 cout<<"Enter the element to be inserted : ";

 cin>>a1[i-1];

 cout<<"Array after inserting the element : ";

 n = n+1;

 display(a1 , n);

}

cout<<"\n\nEnter position (form 1 to "<<n<<") from where you want to delete the element : ";

cin>>j;

if(i > n)

{

 cout<<"Invalid position";

}

else

{

 for(int x = j-1 ; x < n-1 ; x++)

 {

  a1[x] = a1[x+1];

 }

 cout<<"Array after deleting the element : ";

 n = n-1;

 display(a1 , n);

}

return 0;

}

Output:

Enter number of elements : 5

Enter elements in array :

1

2

3

4

5

Array : 1       2       3       4       5

Enter position (form 1 to 5) at which you want to insert the element : 3

Enter the element to be inserted : 10

Array after inserting the element : 1   2       10      3       4       5

Enter position (form 1 to 6) from where you want to delete the element : 4

Array after deleting the element : 1    2       10      4       5

Similar questions