Insert An Element In An Array

Insert An Element In An Array


Write a program to insert a given number at the given position in an array.

import java.io.*;

class Array_Insert
 {
   public static void main ( String agrs[])throws IOException
   {
      BufferedReader obj= new BufferedReader( new InputStreamReader(System.in));
      System.out.println("Enter the length of array : ");
    int n = Integer.parseInt(obj.readLine());

    int a[] = new int[n+1];
    int i, p,j,b;
    boolean flag = false;

    System.out.println("Enter "+n+" elements for the array :");
    for(i = 0; i < n; i++)
    {
        a[i] = Integer.parseInt(obj.readLine());
    }

    System.out.println(" \nEnter the element to be inserted :"); 
    b = Integer.parseInt(obj.readLine());

    System.out.println("\nEnter the position of insertion :");
    p = Integer.parseInt(obj.readLine());


      for(i = 0; i < n; i++)
    {
        if( i + 1 == p){

            for(j = n; j >= p; j--)
                a[j] = a[j-1];

             a[p-1] = b;       
            flag = true;
            n++;
            break;
        }
    }

    if(flag){
        System.out.println("Array after inserting the element "+ p + " at the position + b + " : ");

    for(i = 0; i < n; i++)
    System.out.print(a[i] + " ");
    }
    else{
        System.out.println("Element not found.");
    }

  }//end of main
}//end of class

Have something to say? Log in to comment on this post.

0 comments