Elements to be added so that all elements of a range are present in array | C ++ program for above implementation ; Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNum ( int arr [ ] , int n ) { int count = 0 ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] != arr [ i + 1 ] && arr [ i ] != arr [ i + 1 ] - 1 ) count += arr [ i + 1 ] - arr [ i ] - 1 ; return count ; } int main ( ) { int arr [ ] = { 3 , 5 , 8 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countNum ( arr , n ) << endl ; return 0 ; }