Printing a reverse array!

Hey guys, I'm having a little trouble figuring out what exactly to put into my print_reverse_array function, I've tried countless times and it doesn't every work out correctly. The program is supposed to pull 10 numbers from an array in a file and print the array in reverse. Thanks for any help guys!!!

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
46
47
48
49
50
51
52
53
  #include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <fstream>

using namespace std;
void format();
void print_array(int[],const int);

int main()
{
	ifstream infile;
	const int arraysize = 10;
	int num_arr[arraysize] = {0};
	infile.open("E:\\c++\\ArrayNumbers.txt");

	if (!infile)
	{
		cerr << "File not found!" << endl;
		exit(1);
	}

	int index = 0;

	infile >> num_arr[index];

	while(infile)
	{
		index++;
		infile >> num_arr[index];
	}
	print_array(num_arr,arraysize);

	infile.close();

	return(0);
}


void print_array(int n[], const int s)
{
	for(int i=0;i<s;i++)
		cout << n[i] << " ";
	cout << endl;
}

void print_reverse_array(int n[], const int s)
{
	
}

So you have the code to show the array in the correct order, the line you need to change is the for loop below, have a go at what you think it should be and ask questions if stuck.

for( int I = 0; I < s; i++ )

I've given you a hint by making the bit's to change bold :-)
1
2
3
4
5
6
void print_reverse_array(int n[], const int s)
{
	for(int i=0;i<s;i++)
		cout << n[s - i - 1] << " ";
	cout << endl;
}
Thank you, Moooce and coder777, I figured out I needed to take out my original print_array function for it to work properly. Thanks for your help! :D
You might also consider using pointer arithmetic a little more directly:

1
2
3
4
5
6
7
8
9
void print_reverse_array(int n[], const int s)
{
    int* nth = n + s ;

    while (nth != n)
        cout << *(--nth) << " " ;

    cout << '\n' ;
}


I find that a little more readable, but your mileage may vary. ;)
Topic archived. No new replies allowed.