# Convert given array to Arithmetic Progression by adding an element in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to convert given array to arithmetic progression by adding an element.

For this we will be provided with an array. Our task is to convert the given array into an arithmetic progression by adding a single element to it and return the added element. If it is not possible, return -1.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
//returning the number to be added
int print_number(int arr[], int n){
sort(arr,arr+n);
int d = arr - arr;
int numToAdd = -1;
bool numAdded = false;
for (int i = 2; i < n; i++) {
int diff = arr[i] - arr[i - 1];
if (diff != d) {
return -1;
if (diff == 2 * d) {
numToAdd = arr[i] - d;
//if number has been added
}
//if not possible
else
return -1;
}
}
//returning last element +
//common difference
if (numToAdd == -1)
return (arr[n - 1] + d);
//else return the chosen number
}
9