Check if an array contains all elements of a given range | C ++ Code for Check if an array contains all elements of a given range ; Function to check the array for elements in given range ; Range is the no . of elements that are to be checked ; Traversing the array ; If an element is in range ; Checking whether elements in range 0 - range are negative ; Element from range is missing from array ; All range elements are present ; Driver code ; Defining Array and size ; A is lower limit and B is the upper limit of range ; True denotes all elements were present ; False denotes any element was not present
#include <iostream> NEW_LINE using namespace std ; bool check_elements ( int arr [ ] , int n , int A , int B ) { int range = B - A ; for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( arr [ i ] ) >= A && abs ( arr [ i ] ) <= B ) { int z = abs ( arr [ i ] ) - A ; if ( arr [ z ] > 0 ) { arr [ z ] = arr [ z ] * -1 ; } } } int count = 0 ; for ( int i = 0 ; i <= range && i < n ; i ++ ) { if ( arr [ i ] > 0 ) return false ; else count ++ ; } if ( count != ( range + 1 ) ) return false ; return true ; } int main ( ) { int arr [ ] = { 1 , 4 , 5 , 2 , 7 , 8 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int A = 2 , B = 5 ; if ( check_elements ( arr , n , A , B ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }