Array Practice-Insert Element At Given Position


import java.util.*;

public class insertElementAtGivenPosition {
   
   static void insertElementInArray(int array[], int noToInsert, int positionToInsert, int arrayLength)
   {
     for(int i = arrayLength -1; i > positionToInsert; i--)
     {
       array[i] = array[i-1];
     }
     array[positionToInsert] = noToInsert;
   }
  
  
    public static void main(String[] args) {
      
      int array[] = new int[4];
      array[0] = 1;
      array[1] = 2;
      
      int noToInsert = 3;
      int positionToInsert = 2;
      
      int arrayLength = array.length;
      System.out.println("Befor array");
      for(int i = 0; i < arrayLength; i++)
      {
        System.out.println(array[i]);
      }
      
      System.out.println("array length is: "+arrayLength);
      
      insertElementInArray(array, noToInsert, positionToInsert-1, arrayLength);
      
      System.out.println("after array");
      for(int i = 0; i < arrayLength; i++)
      {
        System.out.println(array[i]);
      }
      
  }
}

Comments

Popular Post

MCQ questions for graphics class method in Java

Session 2 TestNG Framework | How to create TestNG Project In Eclipse IDE | With Selenium Test Cases

Print Hello World In Different Programming Languages | Boost Coding Skill | Developer Life

How to run Selenium script when system is locked?

Read Any Type Of JSON File in JAVA | Simple Introduction And Demo Of JavaScript Object Notation