# Thread: Possible to reverse numbers in an array?

1. ## Possible to reverse numbers in an array?

I know it's possible to reverse numbers of a list, but is it possible to do it when using an array?

For an example here is a simple program that asks the user to enter the amount of numbers in the array, asks the users to enter the numbers in the array, and then prints them out.

Code:
```#include<iostream>
using namespace std;

int main()
{
int SIZE;

int counter;

cout << "Enter the size of the array: ";
cin >> SIZE;
int number[SIZE];
for (counter = 0; counter < SIZE; counter++)
{
cout << "Enter number " << (counter + 1) << ": " ;
cin >> number[counter];
}

for (counter = 0; counter < SIZE; counter++)
{
cout << number[counter] << " ";
}
cout << endl;

return 0;
}```
If I enter 1 2 3 4 5 in, is it possible with the code I have, to make the numbers come out 5 4 3 2 1?

2. Sure. Just start counting from the end of the array instead of the beginning and decrement counter.

3. Or access number[SIZE - 1 - i] even.

4. Originally Posted by Clairvoyant1332
Sure. Just start counting from the end of the array instead of the beginning and decrement counter.
Well that's how I figured you would do it but how do you start at the end of the array since the user gets the enter the number of the array.

Like if I knew the array was a size ten I could do
Code:
` for (count = 10; count > number; count--)`
Since I don't know the size of the array, not sure how to do it.

5. Try knowing about dynamic array creation or if you still want to use static ones, in the very start, try initializing your array with null and then after getting input from user, search through the array unless you arrives null and get the index. From here continue, decrementing the loop and printing it. Good Luck.

6. Originally Posted by theCanuck
I know it's possible to reverse numbers of a list, but is it possible to do it when using an array?
Heh, in practice this is generally more complex to do with a list.

There are a few ways you could probably do this though.

You could write a function to reverse an array of any size. This isn't very hard and is good practice.
But the idea for reversing an array, or ANY range of numbers, is you would store two indexes, one at the first element in the array (let's call it START), the other at the end of the array (let's call that END).
Then you would loop through half the array, each time switching array[START + i] and array[END - i], where i represents iterations the loop has completed.

With this method you could reverse a subset of your array.

Or you could print them starting from the end and moving backwards. Or you could have the numbers stored in the array starting at the end.

Popular pages Recent additions