Skip to content

Commit d5c8b88

Browse files
Create InsertArray.java
1 parent 3e796a6 commit d5c8b88

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

InsertArray.java

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

0 commit comments

Comments
 (0)