Java Program to insert element to an array
Program
import java.util.Scanner;
public class InsertElementsToArray {
public static void main(String[] args) {
int newElement;
int i;
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
int inputArray[] = new int [size+1];
System.out.println("Enter the elements of the array: ");
for(i=0; i<size; i++){
inputArray[i] = reader.nextInt();
}
System.out.print("Enter the element which you want to insert: ");
newElement = reader.nextInt();
inputArray[size] = newElement;
System.out.print("Printing array elements after inserting : ");
for(i = 0; i < size; i++) {
System.out.print(inputArray[i]+",");
}
System.out.print(inputArray[size]);
}
}
Output
javac .\InsertElementsToArray.java
java InsertElementsToArray
Enter the required size of the array:
3
Enter the elements of the array:
11
22
33
Enter the element which you want to insert: 44
Printing array elements after inserting : 11,22,33,44