Generate an N | C ++ program for the above approach ; Function to construct an array with given conditions ; Traverse the array arr [ ] ; Stores closest power of 2 less than or equal to arr [ i ] ; Stores R into brr [ i ] ; Print array elements ; Driver Code ; Given array ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArray ( int arr [ ] , int N ) { int brr [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int K = log ( arr [ i ] ) / log ( 2 ) ; int R = pow ( 2 , K ) ; brr [ i ] = R ; } for ( int i = 0 ; i < N ; i ++ ) { cout << brr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 11 , 5 , 7 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructArray ( arr , N ) ; return 0 ; }