INSERTING IN AN ARRAY

//there is a simple program that will insert an element

language=C++

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

int main()
{
    int n,number = 0;

    cout << "Enter number of elements?";

    cin >>n;


    int la[n];

    for(int i = 0; i < n; i++)
    {
        char c;

        scanf( "%d%c",&la[i],&c );

/*input will terminate when enter is pressed or when the array is full and continude by pressing space.*/

        number += 1;

        if(c == '\n')
        {
            break;
        }
    }

    int insert_position,counter;

    cout << "which position do you want to insert?";

    cin >> insert_position;

    if(insert_position > n+1 || insert_position > number + 1)
    {
        cout << "data overflow\n";
        return 0;
    }
    if(insert_position == 0)
    {
        cout << "data underflow";
        return 0;
    }

    counter = number;

    while( counter >= insert_position - 1 )
    {
        la[counter+1] = la[counter];

        counter -= 1;
    }

    cout << "which value do you want to insert?";

    int ITEM;

    cin >> ITEM;

    la[insert_position - 1] = ITEM;

    number += 1;

    cout << "updated linear array:";
    for(int i = 0; i < number; i++)
        cout << la[i] << " ";

    return 0;

}

No comments:

Post a Comment

Kruskal Algorithm

Minimum Cost Spanning Tree By Kruskal Algorithm using priority_queue in c++ #include<bits/stdc++.h> using namespace std; typedef p...