ARRAY INSERTION IN JAVA
EXAMPLE 1: JAVA PROGRAM TO INSERT AN ELEMENT AT THE END OF ARRAY
import java.util.Scanner; //Import the Scanner class
class array_insert
{
public static void main(String args[])
{
int num[] = new int[60];
int i, n, size;
System.out.print("Enter array size: ");
Scanner in = new Scanner(System.in);
size=in.nextInt();
//Insert value in size variable at run time
//size=in.nextInt();
System.out.println("Enter values in array:");
//Scanner in = new Scanner(System.in);
for(i=0; i<size; i++)
{
num[i]=in.nextInt();
}
System.out.print("Enter new value to array: ");
n=in.nextInt();
//Insert value in array
num[size]=n;
size=size+1;
System.out.println("\nArray values after insertion");
for(i=0; i<size; i++)
{
System.out.println(num[i]);
}
}
}
- - - PROGRAM OUTPUT - - -
EXAMPLE 2: JAVA PROGRAM TO INSERT AN ELEMENT IN A SPECIFIC POSITION IN THE ARRAY
import java.util.Scanner; //Import the Scanner class
class array_insert
{
public static void main(String args[])
{
int num[] = new int[60];
int i, j, n, po, size;
int temp;
System.out.print("Enter array size: ");
Scanner in = new Scanner(System.in);
size=in.nextInt();
//Insert value in size variable at run time
//size=in.nextInt();
System.out.println("Enter values in array:");
//Scanner in = new Scanner(System.in);
for(i=0; i<size; i++)
{
num[i]=in.nextInt();
}
System.out.print("Enter the position: ");
po=in.nextInt();
System.out.print("Enter new value to array: ");
n=in.nextInt();
//Insert value in array
size=size+1;
for(i=size-1; i>=0; i--)
{
num[i+1] = num[i];
}
num[po-1]=n;
System.out.println("\nArray values after insertion");
for(i=0; i<size; i++)
{
System.out.println(num[i]);
}
}
}
- - - PROGRAM OUTPUT - - -
0 Comments