Reputation: 39
New to C++ and learning. This program returns the correct output. I changed the function prototype to void to isolate and make sure function is providing correct output.
#include <iostream>
#include <fstream>
void ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
ArraySortToMedian(array, SIZE);
return 0;
}
void ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
cout << "\n" << m;
}
Output:
6
5
3
1
2
4
1
2
3
4
5
6
3.5
When I remove void and replace it with double to return to main() the median value like this.
#include <iostream>
#include <fstream>
double ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
double median;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
median=ArraySortToMedian(array, SIZE);
cout<< "\n" << median << "\n";
return 0;
}
double ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
return(m);
}
Distorted Output:
1
6
5
3
1
2
1
1
2
3
5
6
2.5
When returned its moving the elements of the array that are generated in main() when before when I simply outputted from ArraySortToMedian(). I assume that it has to do with me referencing the beginning address of the array first element. Probably very simple but with my limited experience I'm at a loss with this behaviour. Any help so that I can learn what I'm doing wrong will be appreciated. Thank you.
Upvotes: 0
Views: 277
Reputation: 303206
The problem is your input loop:
int i;
// ... snip ...
while(i < SIZE && infile >> array[i])
i++;
You're never initializing i
, so this is undefined behavior. Maybe it works maybe it doesn't.
If you used a std::vector
instead of an array, this would be easier:
std::vector<int> values;
int next;
while (infile >> next) {
values.push_back(next);
}
And now you're neither size-limited nor do you have to worry about keeping track of an index.
Upvotes: 3