Check if an Array is Symmetric in C++
In this exercise, you will create a function to determine if an array is symmetric. An array is considered symmetric (or a palindrome) if it reads the same forward and backward.
This problem is a classic introduction to Two-Pointer logic and efficient array traversal, as you only need to inspect half of the data to reach a conclusion.
How it works
Efficiency: O(n/2)
We only loop until size / 2. If we reach the middle without mismatches, symmetry is guaranteed.
The Formula
For any index i, we compare it with size - 1 - i.
Pro Tip: Efficiency Matters
Notice that we only loop until size / 2. Why? Because once you've compared the first half with the second half, you've already verified every pair. Checking the whole array would be redundant and double the work for the CPU!
Objective
- 1. Define and initialize an array with test values.
- 2. Implement a boolean function to compare elements from both ends.
- 3. Handle both even and odd length arrays correctly.
- 4. Output a clear result message to the console.
Example C++ Code
#include <iostream>
using namespace std;
bool isSymmetric(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
if (arr[i] != arr[size - 1 - i]) {
return false;
}
}
return true;
}
int main() {
int arr[] = {1, 2, 3, 2, 1};
int size = sizeof(arr) / sizeof(arr[0]);
if (isSymmetric(arr, size)) {
cout << "The array is symmetric." << endl;
} else {
cout << "The array is not symmetric." << endl;
}
return 0;
}