Java Program to Print All Distinct Elements in an Array – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 14 Dec 2020 16:04:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Java Program to Print All Distinct Elements in an Array – Programmerbay https://programmerbay.com 32 32 Java Program to Print All Distinct Elements in Array https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/ https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/#respond Thu, 27 Feb 2020 07:16:52 +0000 https://programmerbay.com/?p=6134 Given an array ‘arr’ that may contain duplicate elements and we need to print distinct elements from that array.

In other words, we need to find all the elements from the given array which have exactly occurred once.

Given Input : 

6,6,3,7,2,3,2

Expected output:

7

Java Program to Print All Distinct Elements in an Array

Program:

public class Main {

        public static void main(String[] args) {
            int[] arr = new int[]{6,6,3,7,2,3,2};
            int count;
            boolean flag = false;
            for(int i=0;i<arr.length;i++)
            {
                 count =  1;
                for(int j=0;j<arr.length;j++)
                {
                    if(arr[i] == arr[j] && (i !=j))
                    {
                        ++count;
                        break;
                    }
                }
                if(count==1) {
                    flag = true;

                    System.out.println(arr[i]);
                }

            }
            if(flag == false)
                System.out.println("Nothing is unqiue");

        }

}

Output:

blog 5

]]>
https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/feed/ 0