- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Print all triplets in sorted array that form AP in C++

In this problem, we are given a sorted array of numbers and we need to find the triplets with are in the form of arithmetic progression.

**An arithmetic progression** is a series of numbers in which the difference between consecutive terms is the same.

**Let’s take an example to understand the problem better −**

Input : array = {2 , 5 , 7, 8 , 9 , 10} Output : 2 5 8 5 7 9 7 8 9 8 9 10

To solve this problem, a simple solution would be running three loops and checking all triplets if they are in AP. but this method has a time complexity of the order n^{3}.

A better solution is using hashing. In this method, we will start from the second element of the array and treat every element as a middle element of the AP and check if it forms the AP or not.

## Example

#include <iostream> using namespace std; void TripletsAP(int arr[], int n){ for (int i = 1; i < n - 1; i++){ for (int j = i - 1, k = i + 1; j >= 0 && k < n;){ if (arr[j] + arr[k] == 2 * arr[i]){ cout<<arr[j]<<"\t"<<arr[i]<<"\t"<< arr[k] << endl; k++; j--; } else if (arr[j] + arr[k] < 2 * arr[i]) k++; else j--; } } } int main(){ int arr[] = {2 , 5 , 7, 8 , 9 , 10}; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The triplets that are in AP are : \n"; TripletsAP(arr, n); return 0; }

## Output

The triplets that are in AP are −

2 5 8 5 7 9 7 8 9 8 9 10

- Related Questions & Answers
- Find all triplets in a sorted array that forms Geometric Progression in C++
- Print all triplets with given sum in C++
- Count Triplets That Can Form Two Arrays of Equal XOR in C++
- Print all permutations in sorted (lexicographic) order in C++
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Python program to print sorted number formed by merging all elements in array
- All unique triplets that sum up to a given value in C++
- Print sorted distinct elements of array in C language
- Count ways to form minimum product triplets in C++
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Print all valid words that are possible using Characters of Array in C++
- Maximum adjacent difference in an array in its sorted form in C++
- Maximum in an array that can make another array sorted in C++
- Maximum value of XOR among all triplets of an array in C++
- Print matrix in antispiral form

Advertisements