อาร์เรย์เก็บสมาชิกชนิดเดียวกัน ดัชนีเริ่มจาก 0 (ตัวแรก index 0)
หาความต่างสัมบูรณ์ระหว่างสมาชิกดัชนีคู่ และสมาชิกดัชนีคี่
- ดัชนีคู่ = 0,2,4,6,8...
- ดัชนีคี่ = 1,3,5,7,9...
ความต่างสัมบูรณ์ = |ค่า1 - ค่า2|
Input: arr = {1, 2, 4, 5, 8}
Output: Absolute difference of even numbers = 4
Absolute difference of odd numbers = 3
คำอธิบาย
สมาชิกดัชนีคู่: 1, 4, 8 → ความต่าง: |4-1|=3, |8-4|=4
สมาชิกดัชนีคี่: 2, 5 → ความต่าง: |5-2|=3
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = { 1, 5, 8, 10, 15, 26 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The array is : \n";
for(int i = 0;i < n;i++) cout<<" "<<arr[i];
int even = 0, 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;
}
ผลลัพธ์
The array is : 1 5 8 10 15 26 Even index absolute difference : 8 Odd index absolute difference : 21