Java Program to print the duplicate elements of an array

In this program, the objective is to identify and print the duplicate elements present in an array. This can be achieved using two loops. The first loop will select an element from the array, and the second loop will iterate through the remaining elements, comparing each one with the selected element. If a match is found, indicating a duplicate, the program will print the duplicate element.

1 2 3 4 2 7 8 8 3

Upon examining the given array, the first occurrence of a duplicate element is found at index 4. This element, with a value of 2, is a duplicate of the element at index 1. Hence, the array contains duplicate elements such as 2, 3, and 8.

Algorithm of a Java Program to print the duplicate elements of an array

STEP 1: Start

STEP 2: Initialize the array arr[] with values {1, 2, 3, 4, 2, 7, 8, 8, 3}.

STEP 3: Print “Duplicate elements in a given array:”.

STEP 4: Repeat STEP 5 to STEP 7 for each index i from 0 to the length of arr[].

STEP 5: Repeat STEP 6 and STEP 7 for each index j from i+1 to the length of arr[].

STEP 6: If the value at arr[i] is equal to the value at arr[j], then:

STEP 7: Print the value at arr[j].

STEP 8: End.

Java Program to print the duplicate elements of an array

public class DuplicateElement {  
public static void main(String[] args) {  
        //Initialize array  
        int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};  
        System.out.println("Duplicate elements in given array: ");  
        //Searches for duplicate element  
        for(int i = 0; i < arr.length; i++) {  
            for(int j = i + 1; j < arr.length; j++) {  
                if(arr[i] == arr[j])  
                    System.out.println(arr[j]);  
            }  
        }  
    }  
}

Output:

Duplicate elements in given array:
2
3
8

In conclusion, the Java program provided aims to identify and print the duplicate elements present in an array. The program follows a step-by-step approach to accomplish this task. It initializes an array with given values, utilizes nested loops to compare each element with the rest of the array, and identifies duplicate elements by checking for matching values. Follow tutorials.freshersnow.com to learn more.