Hi

I coded a program where you can reverse the contents of an array. But I used two arrays to complete this process, I want to make it work by using only one array.

Here is my code so far, it works btw, just need to make it work by using only one array:

#include<iostream>
using namespace std;

int main()
{
    int a[10], b[10],i,j;

    cout << "Enter 10 values for array: ";
    for(i=0;i<10;i++)
    {
        cin >> a[i];
    }
    for(i=0,j=9;i<10;i++,j--)
    {
        b[j] = a[i];
    }
    cout << "\n\nOrginial Array is: ";
    for(i=0;i<10;i++)
    {
        cout << a[i] << ", ";
    }
    cout << "\n\nNew Array is: ";
    for(i=0;i<10;i++)
    {
        cout << b[i] << ", " ;
    }

    return 0;
}

You can do it with a single array and a single value of the type in the array (an int in your case).

Use the single value as a temporary to swap the first and last elements and then the second and penultimate elements and so on.

Or, you could use std::swap, if you're allowed to do that

Edited 1 Year Ago by ravenous: added swap comment

Comments
Good point about std::swap

The std::swap function does use a temporary value when doing the swap, but the user doesn't need to worry about that. This is when standard tools can be helpful, and reduce the amount of code that the user needs to write.

If temporary variables are also not wanted and you're only going to use integral types, you can use the additive swap method:

int a = 3;
int b = 5;

a = a + b;//a=8,b=5
b = a - b;//a=8,b=3
a = a - b;//a=5,b=3

Edited 1 Year Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.