Group
Arrays and Vectors in C++
Objective
1. Define an array and initialize it with some values.
2. Create a function that compares the elements of the array from both ends.
3. The function should return true if the array is symmetric and false otherwise.
4. Test the program with different arrays, including arrays with an even and odd number of elements.
5. Output the result indicating whether the array is symmetric or not.
Implement a function that determines if an array is symmetric.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to check if the array is symmetric
bool isSymmetric(int arr[], int size) {
// Loop through half of the array
for (int i = 0; i < size / 2; i++) {
// Compare the element from the beginning with the corresponding element from the end
if (arr[i] != arr[size - 1 - i]) {
return false; // If a mismatch is found, the array is not symmetric
}
}
return true; // If no mismatch is found, the array is symmetric
}
int main() {
// Define an array with symmetric elements
int arr[] = {1, 2, 3, 2, 1};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
// Call the function to check if the array is symmetric
if (isSymmetric(arr, size)) {
cout << "The array is symmetric." << endl; // Output if the array is symmetric
} else {
cout << "The array is not symmetric." << endl; // Output if the array is not symmetric
}
return 0; // End of program
}
Output
The array is symmetric.