gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
#include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int…
- User
#include using namespace std;
int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);
// Create a temporary array for reversed elements int reversed[size]; // Reverse the array for (int i = 0; i < size; i++) { reversed[i] = arr[size - 1 - i]; } // Print the reversed array cout << "Reversed array: "; for (int i = 0; i < size; i++) { cout << reversed[i] << " "; } return 0;}
- Assistant
Your code successfully reverses the array and prints the reversed elements. Here is a brief explanation and a few suggestions:
What the code does:
- Calculates the size of the array.
- Creates a new array
reversedof the same size. - Copies elements from
arrintoreversedin reverse order. - Prints the contents of the
reversedarray.
Output:
Reversed array: 5 4 3 2 1Suggestions and improvements:
-
In-place reversal (optional): If you want to reverse the original array
arrin place without using additional memory, you can swap elements from start to end as shown below:int start = 0, end = size - 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } -
Use
std::reversefrom<algorithm>(C++ standard library):#include <algorithm> std::reverse(arr, arr + size); -
Printing the reversed array directly without extra array (if reversed in place):
for(int i = 0; i < size; i++) { cout << arr[i] << " "; }
Everything in your code functions correctly given the approach you've taken. Let me know if you'd like help refactoring or improving it!