Check if an Array is Symmetric

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.

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

symmetry_check.cpp Symmetry Array
#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;
}

Console Output:

The array is symmetric.
Related Topics
Palindrome Array Traversal Equality Check Two-Pointer Approach Early Exit Linear Complexity
© C++ Programming Exercises. Master the art of performance coding.