Absolute Difference of all pairwise consecutive elements in an array (C++)?



An array in C++ is a data structure used to store multiple values of the same type in a contiguous block of memory. To know that how values shift from one index to the next, a common and practical technique is to compute the absolute difference between each pair of consecutive elements.

Absolute Difference

The absolute difference is the positive distance between two numbers, regardless of which one is larger. It is computed using the abs() function from the <cmath> library.

Absolute difference between a and b is denoted as |a - b|.

For example, |7 - 3| = 4 and |3 - 7| = 4.

We are given an array of integers, and we need to find the absolute difference between every two consecutive elements in the array.

Consider The following example scenarios to understand the concept better:

Scenario 1

Input: array = {8, 5, 4, 3}
Output: 3 1 1
Explanation:
The absolute differences are |5-8| = 3, |4-5| = 1, |3-4| = 1.

Scenario 2

Input: array = {14, 20, 25, 15, 16}
Output: 6 5 10 1
Explanation:
The absolute differences are |20-14| = 6, |25-20| = 5, |15-25| = 10, |16-15| = 1.

Finding Absolute Difference of All Pairwise Consecutive Elements in an Array

To find the absolute difference between each pair of consecutive elements in an array, follow these steps:

  • Include the <cmath> library to use the abs() function.
  • Initialize a result array to store the differences.
  • Loop through the original array from index 0 to n - 2.
  • At each step, calculate abs(arr[i] - arr[i+1]) and store it in the result array.

C++ Program to Find Absolute Difference of All Pairwise Consecutive Elements in an Array

In this program, we are calculating the absolute difference between each pair of consecutive elements in the given array and storing the result in a new array.:

#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]);
   }
}

int 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] << " ";
   }

   return 0;  
}

Output

The differences array: 6 5 10 1
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-08-01T18:06:10+05:30

632 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements