Adding Element In Array Program in Java
import java.util.Scanner;
public class AddingElementInArray
{
public static void main(String[] args)
{
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.print("Enter the number ar[" + i + "]:");
arr[i] = sc.nextInt();
}
int n = arr.length;
int newarr[] = new int[n + 1];
System.out.print("Enter position:");
int pos = sc.nextInt();
System.out.print("Enter number to be insert:");
int x = sc.nextInt();
for (int i = 0; i < n + 1; i++)
{
if (i < pos - 1)
{
newarr[i] = arr[i];
} else if (i == pos - 1)
{
newarr[i] = x;
} else
{
newarr[i] = arr[i - 1];
}
}
System.out.println("Adding Element in New Array:");
for (int i = 0; i < n+1; i++)
{
System.out.println(newarr[i]);
}
}
}
Output:
Enter the number ar[0]:1 Enter the number ar[1]:2 Enter the number ar[2]:3 Enter the number ar[3]:4 Enter the number ar[4]:5 Enter the number ar[5]:6 Enter the number ar[6]:7 Enter the number ar[7]:8 Enter the number ar[8]:9 Enter the number ar[9]:10 Enter position:5 Enter number to be insert:1000 Adding Element in New Array: 1 2 3 4 1000 5 6 7 8 9 10learn java study java