Trying to print array in reverse

Hi,
As part of a program I'm doing I'm trying to print an array in reverse.
I thought I had figured it out as part of a larger program but it was outputting one of the digits incorrectly. Now when I run it on its own It just gives me the array back in its original state with no reversing. Could you please give me some help with this. My thinking was that if I initialized the i to 11 and decremented it, it would print the array starting at the end and working backwards . This doesn't seem to be the case. I can't use functions for this project as I haven't gotten onto them in my course yet. Any help appreciated thanks.

The values of the array are 8 16 12 6 16 4 8 10 2 16 12 6

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
#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])

{
	ifstream infile("data.dat");
	ofstream outfile("output.dat");
	int list[12];

	
	for (int i = 11; i!=-1; i--)// The variable i is initialised to 11. While i is not equal to -1 decrement i by 1.
	{
		infile >> list[i];//Read in values for array from data.dat
		cout << list[i] << " ";// Outputting the array in reverse order.
		outfile << "The array in reverse order is: " << list[i] << " " << endl;// Outputting the array in reverse order to file.

	}
	cout << endl;

	
		

	return 0;
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    const int N = 12;
    int list[N] = { 8, 16, 12, 6, 16, 4, 8, 10, 2, 16, 12, 6 };
    
    // start at the last position N-1
    // decrement pos at the end of each iteration
    for( int pos = N-1 ; pos >= 0 ; --pos ) std::cout << list[pos] << ' ' ;
    std::cout << '\n' ;
}
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
#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])

{
	ifstream infile("data.dat");
	ofstream outfile("output.dat");
	int list[12];
	
	for (int i = 11; i!=-1; i--)// The variable i is initialised to 11. While i is not equal to -1 decrement i by 1.
	{
		infile >> list[i];//Read in values for array from data.dat
		cout << list[i] << " ";// Outputting the array in reverse order.
	}

	for (int i=0 ; i < 12; i++)
	{
		outfile << "The array in reverse order is: " << list[i] << " " << endl;// Outputting the array in reverse order to file.
	}

	cout << endl;
		

	return 0;
}
Last edited on
Thanks very much. works great. I just moved the cout to the second for loop and it works perfect. Thanks
Topic archived. No new replies allowed.