Insert Element in The Array Algorithm

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Insert Element in the Array

Algorithm:
1. set j := N // N is total element of array =J
2. Repeat steps 3 and 4 while J >=k
3. [move jth element downward] set LA[J+1] := LA[J]
4. [decrease counter] set j := j-1
5. [insert element] set LA[K] := ITEM
6. [reset N] set N := N+1
7. Exit

Code#1
#include<iostream>
using namespace std;
main()
{
int size, element, i, loc, n_val;
cout<<"Enter Array Size :: "; //user will enter size of array
cin>>size;
int array[size];
for(i=0;i<size;i++)
{
cout<<"\nEnter Element("<<i+1<<") :: ";
cin>>array[i]; //user will enter elements one by one
}
cout<<"\nEnter The Location :: ";
cin>>loc; //location where the user wants to insert the new value
loc=loc-1;
cout<<"\nEnter Value :: ";
cin>>n_val; //value that he wants to insert
for(i=size;i>=loc;i--)
{
array[i+1]=array[i]; //incrementing the index number of the values that are
after the location given by the user
}
array[loc]=n_val; // storing the new value in the location given by the user
if(loc > size) //if the user enter a location that exceds the size of array
{
size = loc; // the location given by user becomes that new size of the array
}
cout<<"The New Elements of array are :: ";
for(i=0;i<=size;i++)
{
cout<<"\t"<<array[i]; // displaying the new array
}
}

Code#2
#include<iostream>
using namespace std;
int main()
{
int n[100],position,value,size;
cout<<"Enter Array Size :: "; //user will enter size of array
cin>>size;
int array[size];
for (int i=0; i<size; i++)
{
cout<<"\nEnter the number of elements in the array("<<i+1<<") :: ";
cin>> n[i];
}
cout<<"Enter the New number of element in the array: ";
cin>> value;
cout<<"Enter the position: ";
cin>> position;
for (int i=0; i<position; i++)
{
n[position] = value;
}
for (int i=0; i<size; i++)
{
cout<< n[i] << " ";
}
}

You might also like