Reverse array

How can I get my array to output it's reverse with what I've already created? I'm confused.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 #include <iostream>
#include <stdlib.h>
using namespace std;

const int MAX_INTEGERS = 20; //Max numbers in array always constant

void fill_array(int a[], int size, int& number);



int main()
{
	if (system("CLS")) system("clear"); //clears garbage from screen

	int integers[MAX_INTEGERS], number;

	cout << "This program outputs an array backwards" << endl;

	fill_array(integers, MAX_INTEGERS, number);

	return 0;
}

void fill_array(int a[], int size, int& number)
{
	cout << "Enter up to " << size << " integers.\n"
		<< "Mark the end of the list with a 0.\n";
	int next, index = 0;
	cin >> next;
	while ((next >= 1) && (index < size)) //prompts user for integers until 0 is input
	{
		a[index] = next;
		index++;
		cin >> next;
	}

	number = index;

	cout << "The reverse order of the array is" << endl;
	//
	//
	//Confused on the code here
	

}
If you are just trying to output the reverse then you can start from the last element and work towards the first.
for(int i = size-1; i > -1; --i)


By the way, shouldn't line 30 be
1
2
3
4
5
while(next && index < size)

//or

while(next != 0 && index < size)
What about negative numbers?
Last edited on
My example was wrong, just ignore my post here.
Last edited on
For your reference, just answered yesterday.

http://www.cplusplus.com/forum/beginner/147276/
You can simply reverse the array with the following idea:

1. Swap first item with last item
2. Swap second item with the item before last item
3. Go on until you hit the middle of the array

wow that was so simple and I was making it much more of a problem... Thanks, and yea I just noticed line 30, thanks. Just trying to figure stuff out ahead of time for class and learn stuff on my own before I get assigned something difficult. Thought I'd mess with arrays for a while and self teach : )
Thanks
@Jacobhaha

1
2
3
4
5
int hello = a[index - 1];
	while(hello >= 0)
	{
	    cout << hello-- << ", ";
	}
this does not reverse an array unless they are in ascending order and have a difference of one. You are just creating a variable, assigning it a value of the last element, hoping the value of it is > 0 and then hoping that each consecutive item is one less in value.

Maybe you are thinking hello is a pointer?
@giblit
you are right, now i see it haha. For some reason i just assumed the array was: 1, 2, 3 up to 20 and ended with 0.
Last edited on
Topic archived. No new replies allowed.