DATA STRUCTURES

  • Home
  • DATA STRUCTURES USING C++


Admission Enquiry Form

Arrays.

A technique which is used to store multiple values but of same data type. In array contigious memory locations are formed and every memory location is assigned with unique index number starting from 0.

Insertion in an Array.

Insertion in an array means insert an element in an array at a given location.



Inserting element 25 at index 2 in array.




Algorithm of insertion in an Array

INSERT(A,N,LOC,ITEM)  [A is an array, N number of elements, LOC is location]

Step1. START

Step2. Repeat Step 3 For I <- N to I  ≥  LOC,  I <- I - 1

Step3.      A[I+1] <- A[I] [Moves elements with index I to Right by 1]

Step4.  A[LOC] <- ITEM 

Step5.  N <- N+1 [Reset size to N+1]

Step6.  END




Program 1: Insertion in an Array.

#include<iostream>
using namespace std;
void insert(int array[],int *n,int item,int loc)
{
int i;
for(i=*n-1;i>=loc;i--)
{
array[i+1]=array[i];
}
array[loc] = item;
*n=*n+1;
}
int main()
{
int array[50], loc, i, n, item;

cout<<"Enter number of elements in the array\n";
cin>>n;

cout<<"Enter "<<n<<" elements\n";

for (i = 0; i < n; i++)
{
cin>>array[i];
}
cout<<"Please enter the location where you want to insert an item\n";
cin>>loc;

cout<<"Please enter the item\n";
cin>>item;
loc=loc-1;

insert(array,&n,item,loc);

cout<<"Resultant array is\n";

for (i = 0; i < n; i++)
{
cout<<array[i]<<endl;
}
return 0;
}//end of main




Program 2: Insertion in an Array.

//Array Data structures
#include<iostream>
#define SIZE 10
using namespace std;

int arr[SIZE];
int pos=-1;
void insertEnd(int value)
{
if(pos<SIZE)
{
pos++;
arr[pos]=value;
}
else
{
cout<<endl<<"Array is full...";

}
}//end of function
void display()
{
if(pos>=0)
{
cout<<endl<<"Values of array are:";
for(int i=0;i<=pos;i++)
{
cout<<arr[i]<<" ";
}
}//end of if
else
{
cout<<endl<<"Array is empty...";
}
}//end of function display
void insertBeg(int value)
{
if(pos<SIZE-1)
{
int i;
for(i=pos;i>=0;i--)
{
arr[i+1]=arr[i];
}
arr[0]=value;
pos++;

}
else{
cout<<endl<<"Can't insert...";
}
}//end of insertBeg function
void insertAt(int index,int value )
{
int i;
if(index>=0 && index<=pos)
{
for(i=pos;i>=index;i--)
{
arr[i+1]=arr[i];
}
arr[i]=value;
pos++;
}//end of if
else{
cout<<endl<<"Please check given index";
cout<<endl<<"last item index is "<<pos;
}
}//end of function insertAt

int main()
{
system("cls");
insertEnd(10);
insertEnd(20);
insertEnd(30);
insertAt(2,500);
display();
insertBeg(40);
display();
insertEnd(70);
display();
insertEnd(80);
insertEnd(90);
insertEnd(75);
insertEnd(56);//8
insertEnd(67);
display();
insertEnd(78);
insertEnd(45);
display();
insertBeg(100);
cout<<endl;
system("pause");
}//end of main