- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Absolute Difference of all pairwise consecutive elements in an array (C++)?
In this problem we will see how we can get the absolute differences between the elements of each pair of elements in an array. If there are n elements, the resultant array will contain n-1 elements. Suppose the elements are {8, 5, 4, 3}. The result will be |8-5| = 3, then |5-4| = 1, |4-3|=1.
Algorithm
pairDiff(arr, n)
begin res := an array to hold results for i in range 0 to n-2, do res[i] := |res[i] – res[i+1]| done end
Example
#include<iostream> #include<cmath> using namespace std; void pairDiff(int arr[], int res[], int n) { for (int i = 0; i < n-1; i++) { res[i] = abs(arr[i] - arr[i+1]); } } main() { int arr[] = {14, 20, 25, 15, 16}; int n = sizeof(arr) / sizeof(arr[0]); int res[n-1]; pairDiff(arr, res, n); cout << "The differences array: "; for(int i = 0; i<n-1; i++) { cout << res[i] << " "; } }
Output
The differences array: 6 5 10 1
- Related Articles
- Product of all pairwise consecutive elements in an Arrays in C++
- Absolute Difference of even and odd indexed elements in an Array (C++)?
- Absolute Difference of even and odd indexed elements in an Array in C++?
- Count maximum elements of an array whose absolute difference does not exceed K in C++
- Check if Queue Elements are pairwise consecutive in Python
- Construct an array from GCDs of consecutive elements in given array in C++
- Find elements of array using XOR of consecutive elements in C++
- How to find the absolute pairwise difference among values of a vector in R?
- Rank of All Elements in an Array using C++
- Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++
- C++ program to replace an element makes array elements consecutive
- Find the winner by adding Pairwise difference of elements in the array until Possible in Python
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Absolute sum of array elements - JavaScript
- Maximum sum of pairwise product in an array with negative allowed in C++

Advertisements