Thursday, May 25, 2017

Program in java to insert a number in an unsorted array at any position

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package datastrucarraya;
/**
 *
 * @author arpis
 */
import java.util.Scanner;
public class insunsordedarray {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
        System.out.println(" enter the number of elements in your array");
        int i =sc.nextInt();
        int ar[] = new int[i+10];
        // taking the input of the arrays
        System.out.println("enter the elements of the arrays");
        for(int j=0;j<(i);j++){
            ar[j]=sc.nextInt();
        }
       
       
       System.out.println("enter the posotion to update");
      int pos =sc.nextInt();
     
       System.out.println("enter the new number "+pos);
       int newnum = sc.nextInt();
        if(ar[(pos-1)]==0&&pos<ar.length){
            System.out.println("array replaced with"+newnum);
          ar[pos-1]=newnum;
      }
        else{
            System.out.println("this position exceeds the array size");
        }
        if(ar[(pos-1)]!=0&&pos<ar.length){
            for(int k=(i-1);k>=pos-1;k--){
               ar[k+1]=ar[k];
            }
             ar[pos-1]=newnum;
        }
         for(int j=0;j<(i+10);j++){
             System.out.println(ar[j]);
        }
       
    }
   
}

1 comment: