Page 293 - Computer science 868 Class 12
P. 293

Program 9     Write a program to insert an element in the array at a specific position.

                   1       import java.util.*;

                   2       class Insert_Array
                   3       {

                   4           int a[];
                   5           int n,x,pos;

                   6           Insert_Array()
                   7           {

                   8               n=0;
                   9               x=0;

                   10              pos=0;
                   11          }

                   12          void input()
                   13          {

                   14              Scanner sc= new Scanner(System.in);
                   15              System.out.print("Enter no. of elements you want in array:");

                   16              n = sc.nextInt();
                   17              a= new int[n+1];

                   18              System.out.println("Enter all the elements:");
                   19              for(int i = 0; i < n; i++)

                   20              {
                   21                  a[i] = sc.nextInt();
                   22              }

                   23              System.out.print("Enter the position where you want to insert element:");

                   24              pos = sc.nextInt();
                   25              System.out.print("Enter the element you want to insert:");
                   26              x = sc.nextInt();

                   27          }
                   28          void insert()

                   29          {
                   30            for(int i = (n-1); i >= (pos-1); i--)

                   31              {
                   32                  a[i+1] = a[i];

                   33              }



                                                                                                                       291
                                                                                                              Arrays   291
   288   289   290   291   292   293   294   295   296   297   298