0

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;
}
4
Contributors
3
Replies
20
Views
1 Year
Discussion Span
Last Post by tinstaafl
1

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 by ravenous: added swap comment

Comments
Good point about std::swap
0

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.

0

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 by tinstaafl

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.