Reverse array

How would i fix the reverse section of this array

#include <iostream>
using namespace std;


//functions prototypes
void readArray(int [], int);
void disArray(int [], int);
void revArray(int [], int);
void minArray(int [], int);
void maxArray(int [], int);
void avgArray(int [], int);

void main()
{
//variables
int myArray[100], size;
char userAnswer;

//instructions
cout<<"Enter the size of the array (smaller than 100)\n";
cin>>size;

do{
cout<<"Select an operation \n";
cout<<"\t 0-Quit the program."<<endl;
cout<<"\t 1-Read an array of size "<<size<<"\n";
cout<<"\t 2-Display the array "<< size<<"\n";
cout<<"\t 3-Reverse the array "<< endl;
cout<<"\t 4-Find max of the array \n ";
cout<<"\t 5-Find min of the array \n ";
cout<<"\t 6-Find the average of all the elements of the array \n ";

cout<<"Your selection:\t";
cin>>userAnswer;

switch (userAnswer)
{
case '0':
cout<<"Good bye!!!"<<endl;
break;
case '1':
readArray(myArray,size);
break;
case '2':
disArray(myArray,size);
break;
case '3':
revArray(myArray,size);
break;
case '4':
maxArray(myArray,size);
break;
case '5':
minArray(myArray,size);
break;
case '6':
avgArray(myArray,size);
break;
default:
cout<<"Error in operation. Re-enter your selection \n";
break;
}

}while (userAnswer!='0');
cout<<"_________ End of Program __________\n\n";

}

void readArray(int myArray[], int size)
{
int i;
cout<<"Input "<< size <<" integer numbers:\n";
for (i=0;i<size;i++)
{
cin>>myArray[i];
}
cout<<endl;
}

void disArray(int myArray[], int size)
{
int i;
for (i=0;i<size;i++)
{
cout<<myArray[i]<<endl;
}
cout<<endl;
}

void revArray(int myArray[], int size)
{
int revArray[100], i;
for (i=size-1;i>=0;i--)
{
revArray[size-1-i]=myArray[i];
}

cout<<myArray[i]<<" "<<endl;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void reverse_array( int array[], int size )
{
    if( size > 1 )
    {
        int left = 0 ; // position of first element
        int right = size - 1 ; // // position of last element

        while( left < right )
        {
            // #include <algorithm>
            std::swap( array[left], array[right] ) ;

            ++left ; // position of next element from left
            --right ; // position of next element from right
        }
    }
}
1
2
3
4
void reverse_array(int array[])
{
     std::reverse(std::begin(array),std::end(array));
}
iQChange, your code will not work, because array size can not be reliably determined in compile time and will result in template substitution failure.

You can either make your function templated (losing ablity to use non-static arrays) or add additional parameter size and computing endpointer manually.
Thank you
Topic archived. No new replies allowed.