Absolute Difference of even and odd indexed elements in an Array (C++)?

C++Server Side ProgrammingProgramming

Here we will see how we can get the absolute differences of odd and even indexed elements in an array. The absolute difference indicates that if the difference of one pair is negative, the absolute value will be taken. For an example, let the numbers are {1, 2, 3, 4, 5, 6, 7, 8, 9}. So the even position elements are 1, 3, 5, 7, 9 (starting from 0), and odd place elements are 2, 4, 6, 8. So the difference for even placed data are |1 - 3| = 2, then |2 - 5| = 3, |3 - 7| = 4 and |4 - 9| = 5 similarly the differences of odd number of places will be 4.

Algorithm

offEvenDiff(arr, n)

begin
   even := 0
   odd := 0
   for i := 0 to n-1, do
      if i is even, then
         even := |even – arr[i]|
      else
         odd := |odd – arr[i]|
   done
   return (odd,even)
end

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
void oddEvenDiff(int arr[], int n, int &o, int &e) {
   int even = 0;
   int odd = 0;
   for (int i = 0; i < n; i++) {
      if (i % 2 == 0) {
         even = abs(even - arr[i]); //get the even difference
      } else {
         odd = abs(odd - arr[i]);
      }
   }
   e = even;
   o = odd;
}
main() {
   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   int odd, even;
   oddEvenDiff(arr, n, odd, even);
   cout << "The odd and even differences are: " << odd << " and " << even;
}

Output

The odd and even differences are: 4 and 5
raja
Published on 24-Jul-2019 16:05:07
Advertisements