Grupo
Arrays y Vectores en C++
Ojetivo
1. Defina un array e inicialícelo con algunos valores.
2. Cree una función que compare los elementos del array desde ambos extremos.
3. La función debe devolver verdadero si el array es simétrico y falso en caso contrario.
4. Pruebe el programa con diferentes arrays, incluyendo arrays con un número par e impar de elementos.
5. Genere el resultado indicando si el array es simétrico o no.
Implemente una función que determine si un array es simétrico.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
The array is symmetric.
Comparte este ejercicio C++