Grupo
Arrays y Vectores en C++
Ojetivo
1. Define un array con varios elementos.
2. Implementa una función o lógica para intercambiar los elementos del array.
3. Comienza desde ambos extremos del array e intercambia los elementos hasta llegar al centro.
4. Genera el array invertido.
5. Prueba el programa con diferentes arrays para asegurarte de que funciona correctamente.
Escribe un programa que invierta un array.
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 reverse an array
void reverseArray(int arr[], int size) {
int temp; // Temporary variable for swapping
// Loop through the array to swap elements from both ends
for (int i = 0; i < size / 2; i++) {
temp = arr[i]; // Store the current element in temp
arr[i] = arr[size - 1 - i]; // Swap the current element with the element from the other end
arr[size - 1 - i] = temp; // Put the value from temp into the other end
}
}
int main() {
// Define an array of numbers
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Output the original array
cout << "Original array: ";
for (int i = 0; i < size; i++) {
cout << numbers[i] << " "; // Print each element in the array
}
cout << endl;
// Reverse the array
reverseArray(numbers, size);
// Output the reversed array
cout << "Reversed array: ";
for (int i = 0; i < size; i++) {
cout << numbers[i] << " "; // Print each element of the reversed array
}
cout << endl;
return 0; // End of program
}
Salida
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
Comparte este ejercicio C++