-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert_an_element.java
More file actions
44 lines (30 loc) · 1019 Bytes
/
insert_an_element.java
File metadata and controls
44 lines (30 loc) · 1019 Bytes
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
import java.util.*;
public class insert_an_element{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("enter size of array - ");
int n=sc.nextInt();
int a[] = new int[n+1];
int item = 189;
System.out.print("enter position where you want to insert - ");
int k = sc.nextInt();
System.out.print("enter elements - ");
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
if(k<=n){
int j = n;
while (j >= k) {
a[j] = a[j - 1];
j--;
}
a[k - 1] = item;
n++;
System.out.println("Updated array after inserting element at position " + k + ":");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}}
else
System.out.println("insertion not possible");
}
}