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
Post a Comment