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

C++Server Side ProgrammingProgramming

An array is a container of multiple elements of the same data type. The index of elements start from 0 i.e. first element has index 0.

In this problem, we need to find the absolute difference between two even indexed number and two odd indexed numbers.

Even indexed number = 0,2,4,6,8….

Odd indexed number = 1,3,5,7,9…

Absolute difference is the modulus of difference between two elements.

For example,

Absolute difference of 15 and 7 = (|15 - 7|) = 8

Input: arr = {1 , 2, 4, 5, 8}
Output :
Absolute difference of even numbers = 4
Absolute difference of odd numbers = 3

## Explanation

Even elements are 1, 4,8

Absolute difference is

(|4 - 1|) = 3 and (|8 - 4|) = 4

Odd elements are 2,5

Absolute difference is

(|5- 2|) = 3

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = { 1, 5, 8, 10, 15, 26 };
int n = sizeof(arr) / sizeof(arr);
cout<<"The array is : \n";
for(int i = 0;i < n;i++){
cout<<" "<<arr[i];
int even = 0;
int odd = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0)
even = abs(even - arr[i]);
else
odd = abs(odd - arr[i]);
}
cout << "Even Index absolute difference : " << even;
cout << endl;
cout << "Odd Index absolute difference : " << odd;
return 0;
}
}

## Output

The array is :
1 5 8 10 15 26
Even index absolute difference : 8
Odd index absolute difference : 21