Program : Check if an array is a palindrome in C++.
Explanation:
To check if an array is a palindrome or not, we need to understand what a palindrome is. A palindrome is a sequence of characters or elements that reads the same forwards and backwards. In the case of an array, it means that the elements of the array should remain the same when read from both ends.
Here’s an example to illustrate the concept:
Consider the array [1, 2, 3, 2, 1]. When we read the array from left to right, it is the same as when we read it from right to left. Hence, it is a palindrome.
On the other hand, let’s take the array [1, 2, 3, 4, 5]. Reading this array from left to right is not the same as reading it from right to left. Therefore, it is not a palindrome.
In general, to determine if an array is a palindrome or not, we compare the elements from the beginning and the end of the array. If they match for each corresponding pair, the array is a palindrome. If there is any mismatch, it is not a palindrome.
It is important to note that the concept of palindromes can be applied to both numeric arrays and character arrays. The logic remains the same – checking for equality of elements in a mirrored fashion.
Remember, this explanation provides a conceptual understanding of checking for an array palindrome. To implement the actual code in a programming language like C++, let’s write code for this :
Solution :
#include <iostream> using namespace std; bool isPalindrome(int array[], int size) { int start = 0; int end = size - 1; while (start < end) { if (array[start] != array[end]) { return false; } start++; end--; } return true; } int main() { const int MAX_SIZE = 100; int size, i; int arr[MAX_SIZE]; cout << "Enter the size of the array: "; cin >> size; cout << "Enter the elements of the array: "; for (i = 0; i < size; i++) { cin >> arr[i]; } bool isPalin = isPalindrome(arr, size); if (isPalin) { cout << "The array is a palindrome."; } else { cout << "The array is not a palindrome."; } return 0; }
Output :
Enter the size of the array: 5 Enter the elements of the array: 1 2 3 2 1 The array is a palindrome.
Dry Run :
Let’s walk through the code written inside the isPalindrome() function with the following inputs:
- Array: [1, 2, 3, 2, 1]
Iteration | start |
end |
array |
Match? |
---|---|---|---|---|
1 | 0 | 4 | 1 2 3 2 1 | Yes |
2 | 1 | 3 | 1 2 3 2 1 | Yes |
3 | 2 | 2 | 1 2 3 2 1 | Yes |
Since all corresponding pairs match, the array is a palindrome.
Want to practice more problems involving Array 1-D ? Click here.