Reverse array using temporary variable C++

2.2k Views Asked by At

Trying to reverse elements in array by using a temporary variable. I can't figure out how to do it

int arraysize = 12;//Size of the array
int option;// Option to be switched
int list[12];//numbers in the array
int total = 0;// Total of all numbers initialised to zero
double average = 0;// average of all numbers
int largestNum = 0;//largest Number
int smallestNum = 6;//first number in the array
int NumberOccurance = 0;// number of times the checked number appears
int usernum;//number to be check for times it appears
int userscaleup;//number to be multiplied by the array contents
int tempnum;// store the value
int endarray;
ifstream infile("data.dat");
ofstream outfile("output.dat");

do
{
    cout << "\t7. Reverse Order\n";

    cin >> option;// Taking in the users option from the menu

    switch (option)

    case 7:

    case 7:

        for (int index = 0; index < arraysize/2; index++, endarray--)
        {
            infile >> list[index];

            int endarray = list[arraysize];// variable endarray holds value of end side of array

            int swapholder = list[index];

            list[index] = list[endarray];//Swap 

            list[endarray] = swapholder;


            cout << list[index] << ' ';

        }
        break;

        while (option != 9);
}

I keep getting output of random negative numbers. Tried multiple solutions. The line I've commented out is also giving random negative numbers.

The arraysize is 12.

have to do this using a temp variable. Could someone please show me the correct method to do this?

Edit: Updated my code. The program is now building but it's crashing when I run it. Any suggestions?

6

There are 6 best solutions below

0
On

This is pseudo code, but should give you an idea. Here I use two counters that move towards the middle from the front and back of the array

count_front = 0;
count_back = max_array_element; //11
While ( count_front < count_back ) {

    temp_var = array[count_front];
    array[count_front] = array[count_back];
    array[count_back] = temp_var;
    count_front++;
    count_back--;

}
0
On

The temporary variable is for swapping: t=list[1]; list [1]=list[2]; list[2]=t; To reverse an array, swap the first and last elements (min and max), then the next-lowest (min+1, max-1) until min >= max.

1
On

Try:

int temp = 0;
for (int index = 0, backwardsIndex = arraysize - 1; index < arraysize / 2; index++, backwardsIndex--)
{
    temp=list[index];
    list[index]=list[backwardsIndex];
    list[backwardsIndex]=temp;
}
4
On

your index size is 12 and you are adding 11 to the index, so at index 2 it will go to index 13.... that is out of the array's range..

if you are trying to reverse it (as in make first last and last first) it needs to look something like this:

    int otherside = arraysize; //set the otherside at the end of the array
    for (int index = 0; index < arraysize/2; index++)
        {
            int swapholder = list[index];    // V
            list[index] = list[otherside];   // Swap them
            list[otherside] = swapholder;    // ^

            otherside =-1; //move backward from end.
                           // moving forward from beginning is the index++

            cout << list[index] << '  ' << list[otherside] <<'/n';

        }

this means you define 2 vars, 1 at begining and 1 at end, you take the one at begining and hold it in a temp, take the last and save it at first and then take the temp and save it at the last... the you move forward once from beginning and back once from end, and repeat.. the repetition should be half of the array's size because it is moving in from both directions at once thus half the amount of movement is needed

EDIT: there are 2 case 7: ,get rid of one, that must be what is causing the crash!

1
On

Simply, let the standard libary function std::reverse do the work for you. (If your goal is not to implement this yourself as an exercise)

3
On

Don't use an array unless it's somehow required. Use a std::vector instead. ( requires you to #include <vector> ).

Then you can simply do something like:

std::vector< int > list;
// fill vector. usually with list.push_back( item );

std::reverse( list.begin( ) , list.end( ) );

If you wanna keep using an array you can reverse it like this:

std::reverse( std::begin( list ) , std::end( list ) );

No need for loops and swapping.


If you can't use std::reverse:

First of all if you declare a max size of an array use it and declare it as const and write it uppercase so you see the difference!

const int ARRAY_SIZE = 12; // const can't be changed runtime.

int list[ARRAY_SIZE]; // Not a good idea to name it list since it's not a list!

Next:

Split the loops no need for a complicated construction of loops.

First fill the array:

// fill array
for( int i = 0 ; i < ARRAY_SIZE ; ++i )
{
    infile >> list[i];
}

Then:

// declare this outside and give it a std. value so you don't redeclare it every run of the loop
int swapHolder       = 0;

// reverse array
for( int i = 0 ; i < ARRAY_SIZE / 2 ; ++i )
{
    swapHolder                  = list[i]; // save the value of first position
    list[i]                     = list[ARRAY_SIZE - 1 - i]; // fill it with the lastPosition - 1 - i
    list[ARRAY_SIZE - 1 - i]    = swapHolder; // replace lastPosition - 1 - i 
}

ARRAY_SIZE - 1 because the array might contain 12 values but it starts at 0 so it's index is 0 - 11.

Working example.

Also:

case 7:

case 7:

makes no sense.