Program to insert an element in an array
import java.util.Scanner;
public class Rkin
{
public static void main(String[] args)
{
int pos,item,n;
Scanner s=new Scanner(System.in);
System.out.println("Enter Size Of Array :");
n=s.nextInt();
int[] a;//declaration of array
a=new int[n+1]; // Creation of array with given size plus one
for(int i=0;i<n;i++)
{
System.out.printf("enter a[%d] = ",i);
a[i]=s.nextInt();
}
System.out.print("ARRAY before inserting an element :\n");
for(int i=0;i<n;i++)
{
System.out.print( a[i] +" ");
}
for(int i=0;i<n;i++)
System.out.printf("\nAddress:%h ---array : a[%d] ---- data :%d position : %d",i*4,i,a[i],i+1);
System.out.print("\nenter the position of the item :\n");
pos=s.nextInt();
System.out.print("\nenter the item to be inserted :\n");
item=s.nextInt();
pos=pos-1;
for(int j=n-1;j>=pos;j--)
{
a[j+1]=a[j];
}
a[pos]=item;
for(int i=0;i<n+1;i++)
{
System.out.print( a[i] +" ");
}
for(int i=0;i<n+1;i++)
System.out.printf("\nAddress:%h ---array : a[%d] ---- data :%d position : %d",i*4,i,a[i],i+1);
}
}
output:
import java.util.Scanner;
public class Rkin
{
public static void main(String[] args)
{
int pos,item,n;
Scanner s=new Scanner(System.in);
System.out.println("Enter Size Of Array :");
n=s.nextInt();
int[] a;//declaration of array
a=new int[n+1]; // Creation of array with given size plus one
for(int i=0;i<n;i++)
{
System.out.printf("enter a[%d] = ",i);
a[i]=s.nextInt();
}
System.out.print("ARRAY before inserting an element :\n");
for(int i=0;i<n;i++)
{
System.out.print( a[i] +" ");
}
for(int i=0;i<n;i++)
System.out.printf("\nAddress:%h ---array : a[%d] ---- data :%d position : %d",i*4,i,a[i],i+1);
System.out.print("\nenter the position of the item :\n");
pos=s.nextInt();
System.out.print("\nenter the item to be inserted :\n");
item=s.nextInt();
pos=pos-1;
for(int j=n-1;j>=pos;j--)
{
a[j+1]=a[j];
}
a[pos]=item;
for(int i=0;i<n+1;i++)
{
System.out.print( a[i] +" ");
}
for(int i=0;i<n+1;i++)
System.out.printf("\nAddress:%h ---array : a[%d] ---- data :%d position : %d",i*4,i,a[i],i+1);
}
}
output:
No comments:
Post a Comment