This is a Java Program to Insert an Element in a Specified Position in a Given Array.
Enter size of array and then enter all the elements of that array. Now enter the element you want to insert and position where you want to insert that element. We shift all the elements in the array from that location by one and hence insert the element easily.
Here is the source code of the Java Program to Insert an Element in a Specified Position in a Given Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Insert_Array
{
public static void main(String[] args)
{
int n, pos, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n+1];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the position where you want to insert element:");
pos = s.nextInt();
System.out.print("Enter the element you want to insert:");
x = s.nextInt();
for(int i = (n-1); i >= (pos-1); i--)
{
a[i+1] = a[i];
}
a[pos-1] = x;
System.out.print("After inserting:");
for(int i = 0; i < n; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n]);
}
}
Output:
$ javac Insert_Array.java $ java Insert_Array Enter no. of elements you want in array:6 Enter all the elements: 2 4 6 9 4 5 Enter the position where you want to insert element:3 Enter the element you want to insert:7 After inserting:2,4,7,6,9,4,5
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Programming MCQs
- Apply for Java Internship
- Buy Programming Books
- Practice BCA MCQs
- Apply for Information Technology Internship