Monday, April 25, 2022

How to add an element in an array in given position

     How to add an element in an array in given position


public class Demo {

public static void main(String args[]) {

int arr[] = new int[5];

arr[0]=1;

arr[1]=2;

arr[2]=3;

arr[3]=4;

int x = 5,pos=3; // x = number to be added in the array , pos = position

int n=4; //length of array

n++;

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

arr[i] = arr[i-1];

}

arr[pos-1] = x;

//print the array

for (int i=0;i<arr.length;i++) {

System.out.println(arr[i]);

}

}

}


No comments:

Post a Comment

Concurrent Hashmap in java

  A ConcurrentHashMap is a thread-safe implementation of the Map interface in Java. Unlike a HashMap , which is not thread-safe and can ca...