0% found this document useful (0 votes)
12 views3 pages

Practical Number 1 - 102620

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)
12 views3 pages

Practical Number 1 - 102620

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/ 3

Practical Number: 1

Write a program to insert a new element at end as well as at a given position in


an array.
Sol: Array is a type of data structure in which elements are stored at contiguous
memory location.
To insert an element in array the basic idea is that, get the position and the new
element from the user then iterate over the array from the end and shift each
element to its next index until we found the position as soon as we get the
position put the new element to that index.

#include<iostream>
using namespace std;
void insertion(int arr[],int n,int pos,int value){
for(int i=n; i>=0; i--){
arr[i+1] = arr[i];
if(i == pos){
arr[i] = value;
break;
}
}
}

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

int pos,value;
cout<<"Enter position where you want to insert an element : ";
cin>>pos;
cout<<"Enter element you want to insert : ";
cin>>value;

insertion(arr,n,pos,value);
cout<<"Resultant array : ";
for(int i=0; i<=n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
Output:

You might also like