1import java.util.Scanner;
2public class InsertElement
3{
4 public static void main(String[] args)
5 {
6 int number, position, insert;
7 Scanner sc = new Scanner(System.in);
8 System.out.println("Please enter number of elements in array: ");
9 number = sc.nextInt();
10 int[] arrNumbers = new int[number + 1];
11 System.out.println("Please enter " + number + " elements: ");
12 for(int a = 0; a < number; a++)
13 {
14 arrNumbers[a] = sc.nextInt();
15 }
16 System.out.println("Please enter position to insert element: ");
17 position = sc.nextInt();
18 System.out.println("Please enter element you want to insert: ");
19 insert = sc.nextInt();
20 for(int a = (number - 1); a >= (position - 1); a--)
21 {
22 arrNumbers[a + 1] = arrNumbers[a];
23 }
24 arrNumbers[position - 1] = insert;
25 System.out.println("After inserting element: ");
26 for(int a = 0; a < number; a++)
27 {
28 System.out.print(arrNumbers[a] + ",");
29 }
30 System.out.print(arrNumbers[number]);
31 sc.close();
32 }
33}
1// ! IMPORTANTE !
2// in JAVA an array is not the same as an ArrayList object!!
3// 1 - declare, instanciate and populate
4int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
5// 2 - declare and instanciate an int array with maxSize
6// note: the index goes between 0 and maxSize-1
7int newarr[] = new int[maxSize];
8// 2.1 - insert the value n on the position pos
9newarr[pos] = n;
10// 2.2 - insert values recursively
11for (i = 0; i < maxSize; i++) { newarr[i] = arr[i]; }