Thursday 26 June 2014

C++ program to delete an element at nth position in an array


Here is a C++ program to delete an element at nth position in an array


 SOURCE CODE OUTPUT
#include<iostream>
using namespace std;
int main()
{
    int i,a[20],flag=0,num,n,element;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    cout<<"Enter element to be deleted ";
    cin>>element;
    for(i=0;i<num;i++)
    {
        if(a[i]==element)
        {
            for(int y=i;y<num;y++)
               a[y]=a[y+1];
            flag=1;
            i--;
        }
    }
    if(flag==0)
    {
        cout<<"Element not found ";
        return 0;
    }
    cout<<"After deleting : ";
    for(int i=0;i<num-1;i++)
        cout<<a[i]<<" ";
    return 0;
}

Any questions regarding to program please write in comments.

No comments:

Post a Comment