Question
print positions of all duplicate elements in an array to be searched.
example:
arr1={1,2,1,3,1,4,5}
elements to be searched:1
output :1
found at positions:
0
2
4
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class positionsOfDuplicateElementsToBeSearched
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr1;
int n=0,i=0,item=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no. of elements in the array");
n = sc.nextInt();
System.out.println("Enter numbers in array");
arr1=new int[n];
for(i=0;i< n;i++)
{
arr1[i]=sc.nextInt();
}
System.out.println("Enter element to be searched in an array");
item=sc.nextInt();
System.out.println();
System.out.println(item+" found at position/positions:" );
for ( i = 0; i < n; i++)
{
if(arr1[i]==item)
{
System.out.println(i);
}
}
}
}