How to delete or remove the element in array || Interview Questions in java.
==========================================
import java.util.Scanner;class RemovedAElement
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter How many element to insert:");
int n=sc.nextInt();
System.out.println("Enter "+n+" element:");
//Create the element based on the n
int arr[]=new int[n];
//Insert element in arrays
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
//Take the values you have to delete and removed
System.out.println("Enter number to removed:");
int val=sc.nextInt();
//applay the logic to removed the element in arrays
boolean found=false;
for(int i=0;i<arr.length;i++){
//check the values it is avilabled in the arrays or not
if(arr[i]==val){
//if values is matched than
found=true;
//Appaly the logic to removed the val
for(int s=i;s<n-1;s++){
arr[s]=arr[s+1];
}
n--;
}
}
//if number is not found in the Arrays
if(found==false)
System.out.println("Number is not found!");
//Display the Final result of the Array
System.out.println("After removal element in array:");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
//For next line
System.out.println();
}
}
------------------------------------------------------------------------
Output:
Comments
Post a Comment