Group
Arrays and Vectors in C++
Objective
1. Define an array with several elements.
2. Implement a function or logic to swap elements in the array.
3. Start from both ends of the array and swap the elements until you reach the middle.
4. Output the reversed array.
5. Test the program with different arrays to ensure it works correctly.
Write a program that reverses an array.
Example C++ Exercise
Show C++ Code
#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
}
Output
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1