I know that I am not supposed to be posting homework questions, however, I am so stumped. I had asked all my friends, searched online, and checked other forums here with no help at all, so please help me.
The question is:
Write an reverse function:
This function should take 2 parameters: a 1D int array and the number of elements.
It should reverse the order of the elements. It should not return anything.
Hint: You can use the swap function to swap two elements, for example swap(a[i], a[j]) would swap a[i] and a[j].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <algorithm>
using namespace std;
void reverse(int a[], int size) {
for( int x = 0; x < size; x++){
for (int y = size; y >= 0; y--){
swap ( a[x], a[y]);}
}
}
int main (){
int a[4] = {7, 2, 8, 3};
int b[5] = {3, 4, 5, 6, 7};
reverse(a, 4);
reverse(b, 5);
cout << "Array a reversed: ";
for (int i = 0; i < 4; ++i)
cout << a[i] << " ";
cout << endl;
cout << "Array b reversed: ";
for (int i = 0; i < 5; ++i)
cout << b[i] << " ";
cout << endl;
return 0;
}
|
The code doesn't work and I am having trouble understanding why. I had tried to pick apart the code and understand what I am making each loop do but the result is making me confused because it is not what I am thinking it is.
Any help is appreciated. Thank you for your time.