-
Notifications
You must be signed in to change notification settings - Fork 2
/
InsertArray.java
48 lines (26 loc) · 867 Bytes
/
InsertArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;
public class InsertArray
{
public static void main(String args[])
{
int a[]; // only an array reference
int n;
int pos, element;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");
n = sc.nextInt();
a = new int[n+1]; // memory is allocated to the array. here it is a dynamic array
System.out.println("Enter values into array...");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
System.out.println("Enter the new element to insert & position: ");
element = sc.nextInt();
pos = sc.nextInt();
for(int i=n;i>pos;i--) // shift all the elements towards right
a[i] = a[i-1];
a[pos] = element;// insert the new element
System.out.println("\n Array after inserting new element:");
for(int i=0;i<n+1;i++)
System.out.print(a[i]+" ");
}
}