Check if an array contains only one distinct element | C ++ program for the above approach ; Function to find if the array contains only one distinct element ; Assume first element to be the unique element ; Traversing the array ; If current element is not equal to X then break the loop and print No ; Compare and print the result ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void uniqueElement ( int arr [ ] , int n ) { int x = arr [ 0 ] ; int flag = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != x ) { flag = 0 ; break ; } } if ( flag == 1 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElement ( arr , n ) ; }