Convert given array to Arithmetic Progression by adding an element | C ++ implementation of the approach ; Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible  to add another number ; If the current different is twice the common difference then a number can be added midway from current and previous element ; Number has been chosen ; It 's not possible to maintain  the common difference ; Return last element + common difference if no element is chosen and the array is already in AP ; Else return the chosen number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumToAdd ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int d = arr [ 1 ] - arr [ 0 ] ; int numToAdd = -1 ; bool numAdded = false ; for ( int i = 2 ; i < n ; i ++ ) { int diff = arr [ i ] - arr [ i - 1 ] ; if ( diff != d ) { if ( numAdded ) return -1 ; if ( diff == 2 * d ) { numToAdd = arr [ i ] - d ; numAdded = true ; } else return -1 ; } } if ( numToAdd == -1 ) return ( arr [ n - 1 ] + d ) ; return numToAdd ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 11 , 13 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getNumToAdd ( arr , n ) ; }