Copyright © Programs ++
Design by Dzignine
Saturday 4 February 2012

Insertion in an integer array

Insertion in an array is a widely used practice used when programming with C/C++. Simply , it involves inserting a value from a user and inserting in an array. Now, how this is done is interesting and simple :-). First we create the array (simple!!! ), then we prompt the user to enter the position where he/she wants to insert and finally, the user is prompted to enter the value to insert in the array. Consider an example, 

Suppose the array initially contains the following values, along with their positions :-
Element 0 : 3
Element 1 : 7
Element 2 : 89
Element 3 : 8
Then inserting any value(say 145) at position '1', then the new array would be like this :-
Element 0 : 3
Element 1 : 145
Element 2 : 7
Element 3 : 89
Element 4 : 8
Who la, the value 145 has been inserted at the 1st position in the array.
Note : Notice, that the size of the array has increased(obviyo!!!) , so always take the size of the array one greater than the no of elements you want to have. This will prevent overwrite problems in the array.
Consider the following snippet of code for a better understanding.

// Program to insert element in an array (for GCC compliler package and similar compilers)

#include <iostream>
// function to insert elements in the array
int insertion_array(int array[],int s,int pos,int val)
{
     for (int i=s; i>=pos; i--) // shifts every element one step below
     {
          array[i+1] = array[i];
     }
     array[pos] = val; // inserts the given value at the specified position
     s++;                  // increments the size, as one extra element is now inserted
     return s;
}

int main()
{
     int size,value,position;
     int arr[21];
     std::cout<<" Enter the no of elements you want in the array (max 20) : ";
     std::cin>>size;

     // prompts the user to enter elements in the array
     for (int i=0; i<size; i++)
     {
          std::cout<<" \n Element "<<i<<" : ";
          std::cin>>arr[i];
     }
     std::cout<<"\n Enter the position where you want to insert the value : ";
     std::cin>>position;
     std::cout<<"\n Enter the value to insert at the "<<position<<" : ";
     std::cin>>value;
     // calls the above function to insert values in the array
     size = insertion_array(arr,size,position,value);
     std::cout<<" \Insertion successfull !!! , the new array is as follows ";
      // displays the new array
     for (int i=0; i<size; i++)
     {
          std::cout<<"\n Element "<<i<<" : "<<arr[i];
     }
     return 0;
} // end of main
------ OUTPUT ------





















Note : If the console window shuts down immedeaitly, then add std::cin.get(); before return 0; to fix the problem. :)
------ Related Posts ------

Deletion in an array : http://programsplusplus.blogspot.in/2012/02/deletion-in-integer-array.html

0 comments:

Post a Comment

Comment Here....