C++ Programs
Programs (Algorithms) in C++

Array (Insertion, Deletion)

#include<iostream.h>
#include<conio.h>

int a[100],i,n=0,item,pos,j;

void main()
{
clrscr();
int choice;

void Ins_end();
void Ins_pos();
void Del_val();
void Del_pos();
void Display();

while(1)			//Infinite Loop.
{
cout<<"\n\n\n\n---------- Array ---------- \n";
cout<<"\nMain Menu\n\n1. Insert an Elemnet\n
                      2. Insert an Element at given Position\n
                      3. Delete an Element by given Value\n
                      4. Delete an Element from given Position\n
                      5. Exit\n\nEnter your choice : ";
cin>>choice;

switch(choice)
{
case 1:
Ins_end();
break;

case 2:
Ins_pos();
break;

case 3:
Del_val();
break;

case 4:
Del_pos();
break;

case 5:
return;			//Exit

default:
cout<<"\nWrong Input";
}
 }
  }


void Display()			//Display Elemnets of Array.
{
   for(i=1;i<=n;i++)
   {
   cout<<"a["<<i<<"]="<<a[i]<<endl;
   }
}


void Ins_end()			//Insert a New Elemnet at the End of Array.
{
   cout<<"\nEnter Element : ";
   cin>>item;
   n=n+1;
   a[n]=item;
   cout<<"\n\nAfter Insertion :\n\n";
   Display();
}


void Ins_pos()			//Insert a New Elemnet at given Position.
{
   cout<<"\nEnter Element : ";
   cin>>item;
   cout<<"\nEnter Position : ";
   cin>>pos;

   if(pos<1 || pos>n+1)
   {
   cout<<"\nInvalid Position.\n\n";
   return;
   }

   for(j=n;j>=pos;j--)
   {
   a[j+1]=a[j];
   }
   a[pos]=item;
   n=n+1;
   cout<<"\n\nAfter Insertion :\n\n";
   Display();
}


void Del_val()			//Delete a Elemnet whose value is given.
{
int s=0;
   cout<<"\nEnter Value you want to Delete : ";
   cin>>item;

   for(i=1;i<=n;i++)
   {
   if(a[i]==item)
   {
   s=i;
   break;
   }
   }

   if(s==0)
   {
   cout<<"\nThe given value is not in the Array.\n\n";
   return;
   }

   for(j=s+1;j<=n;j++)
   {
   a[j-1]=a[j];
   }
   n=n-1;
   cout<<"\n\nAfter Deletion :\n\n";
   Display();
}


void Del_pos()			//Delete a Elemnet whose position is given.
{
   cout<<"\nEnter Position : ";
   cin>>pos;

   if(pos<1 || pos>n)
   {
   cout<<"\nInvalid Position.\n\n";
   return;
   }

   for(j=pos+1;j<=n;j++)
   {
   a[j-1]=a[j];
   }
   n=n-1;
   cout<<"\n\nAfter Deletion :\n\n";
   Display();
}


Output :-

Array Insert Delete




Powered by Blog - Widget
Face Upward - Widget