Inserting an element in an array in MATLAB
Inserting
an element in an array ( MATLAB & JAVA)
Write a program to insert an element in a particular index position in an array.
MATLAB CODE:
x=input('Enter the array:');
y=input('Enter the position:');
z=input('Enter the number to be inserted:');
b=[];
for i=1:(y-1)
b(i)=x(i);
end
b(y)=z;
for i=(y+1):(length(x)+1)
b(i)=x(i-1);
end
disp(b);
OUTPUT:
Reference Video:
JAVA CODE:
import java.util.Scanner;
class Ha
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length:");
int n=obj.nextInt();
int x[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the number in array:");
x[i]=obj.nextInt();
}
System.out.println("Enter the position");
int y=obj.nextInt();
System.out.println("Enter the number to be inserted:");
int z=obj.nextInt();
int b[]=new int[n+1];
for(int i=0;i<=(y-1);i++)
{
b[i]=x[i];
}
b[y]=z;
for(int i=y+1;i<x.length+1;i++)
{
b[i]=x[i-1];
}
System.out.println("The new array is:");
for(int i=0;i<x.length+1;i++)
{
System.out.print(b[i]+" ");
}
}
}
OUTPUT:
Write a program to insert an element in a particular index position in an array.
MATLAB CODE:
x=input('Enter the array:');
y=input('Enter the position:');
z=input('Enter the number to be inserted:');
b=[];
for i=1:(y-1)
b(i)=x(i);
end
b(y)=z;
for i=(y+1):(length(x)+1)
b(i)=x(i-1);
end
disp(b);
OUTPUT:
Reference Video:
JAVA CODE:
import java.util.Scanner;
class Ha
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length:");
int n=obj.nextInt();
int x[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the number in array:");
x[i]=obj.nextInt();
}
System.out.println("Enter the position");
int y=obj.nextInt();
System.out.println("Enter the number to be inserted:");
int z=obj.nextInt();
int b[]=new int[n+1];
for(int i=0;i<=(y-1);i++)
{
b[i]=x[i];
}
b[y]=z;
for(int i=y+1;i<x.length+1;i++)
{
b[i]=x[i-1];
}
System.out.println("The new array is:");
for(int i=0;i<x.length+1;i++)
{
System.out.print(b[i]+" ");
}
}
}
OUTPUT:
No comments