
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Convert given array to Arithmetic Progression by adding an element in C++
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
#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[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; //if number has been added numAdded = true; } //if not possible else return -1; } } //returning last element + //common difference if (numToAdd == -1) return (arr[n - 1] + d); //else return the chosen number return numToAdd; } int main() { int arr[] = { 1, 3, 5, 7, 11, 13, 15 }; int n = sizeof(arr)/sizeof(arr[0]); cout << print_number(arr, n); }
OUTPUT
9
- Related Articles
- Count of AP (Arithmetic Progression) Subsequences in an array in C++
- Missing Number In Arithmetic Progression using C++
- Adding an element at a given position of the array in Javascript
- Adding an element in an array using Javascript
- Python program to convert tuple into list by adding the given string after every element
- Find the missing number in Arithmetic Progression in C++
- Adding an element to the List in C#
- What is arithmetic progression?
- C program to find the sum of arithmetic progression series
- Finding the missing number in an arithmetic progression sequence in JavaScript
- Adding an element into the Hashtable in C#
- Adding an element at the end of the array in Javascript
- Adding an element at the start of the array in Javascript
- C Program for N-th term of Arithmetic Progression series
- Adding elements of an array until every element becomes greater than or equal to k in C++.

Advertisements