finding the odd/even positions in a list help!

Well I need help trying to display numbers that have the odd number subscript such as x[1], x[3] etc and also for the even x[2], x[4] etc.

how would I do that? Can anyone give me an example?

the numbers were read from a .dat file into an array. The integers are read from the file into positions in the array starting with subscript 1 and continue reading until an end of file condition is encountered.

(each of these displayed on different lines)
Display the entire list on screen
Display the number that appear in the odd position in the list
Display the number that appear in the even position in th list

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

void main()

{
ifstream infile;
ofstream outfile;
int n, num, x[50];

infile.open("numbers.dat");
if(infile.fail())
{
cerr << "Cannot open input file numbers.dat \n";
abort();
}
outfile.open("output.dat");

n = 0;
cout << "The Original list is:" << endl;
while (infile >> ws && !infile.eof())
{
infile >> num;
n = n + 1;
x[n] = num;
cout << setw(4) << num;
}
cout << "The numbers in odd position are:";
for(n = 1; n <= x[n]; n++)
{
if(n % 2 == 1) cout << setw(4) << x[n];
}
cout << endl;
cout << "The numbers in even position are:";
for(n = 1; n <= x[n]; n++)
{
if(n % 2 == 0) cout << setw(4) << x[n];
}

cout << endl;
cout << "Program finished\n";

system ("pause");
}

this seems to work but the only problem is that the numbers from the dat file are
41-50
31-40
21-30
11-20

but when my program only displays numbers from 41-50, 31-40, and 21-30.
It doesn't display 11-20

any suggestions?
Last edited on
closed account (D80DSL3A)
The for loops you're using are unusual.
for(n = 1; n <= x[n]; n++)
The comparison is being made between n and the value stored in the array x[n].
It looks like you're ok until n reaches about 31 or so. If I understand how the values are being stored it looks like x[31] = 11, so the test 31 <= 11 would be false and the loop would end.
This is why you aren't getting the last 10 values output, although the array contains them.

I think you want to keep n unchanged (n = # of array elements) and use a different variable for the loop. Perhaps:
1
2
int i=0;
for(i=1; i<=n; i++)

This will go through all of the array elements.
Also, array indexes start at 0 not 1, but I suppose you can make it work starting at 1. You're just leaving x[0] unused.
Topic archived. No new replies allowed.