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.
Related Posts:
- Check Java Books
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Check Programming Books
- Apply for Java Internship