Home > other >  the output array shows only the last element instead of inserting data at specified location in the
the output array shows only the last element instead of inserting data at specified location in the

Time:11-18

#include <iostream>
using namespace std;

#define max 10

int main()
{
    int items[max];
    int i,n,ub,location,data;

    cout<<"Enter the number of items you want to enter: "<<endl;
    cin>>n;

    ub=n-1;

    if(ub>=max-1){
        cout<<"Array is full!"<<endl;
    }

    else{
        cout<<"Enter "<<n<<" elements:"<<endl;
        for(i=0;i<n;i  ){
            cin>>items[n];
        }

        cout<<"Enter the location where you want to insert:"<<endl;
        cin>>location;
        cout<<"Enter the data you want to insert in location "<<location<<endl;
        cin>>data;

        while(ub>=location){
            items[ub]=items[ub-1];
            ub--;
        }

        items[location]=data;

        cout<<"The array after insertion is as follows: "<<endl;
        for(i=0;i<n;i  ){
            cout<<items[n]<<endl;
        }
    }

}

for an input array of n=5 being let's say {1 ,2 ,3 ,4 ,5 },i want to insert data=19 at location 2 of the array such that the output is {1, 19, 3, 4, 5} but the output i get is {5 ,5 ,5 ,5 ,5}. how can i fox this?
output

CodePudding user response:

You have two issues:

  1. cin>>items[n]; must be cin>>items[i];
  2. cout<<items[n]<<endl; must be cout<<items[i]<<endl;
  • Related