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

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 24-Jul-2019 12:31:45
Advertisements