so I'm having a bit of trouble with this program. The point of the code is to input a list of numbers called grades.txt
into an array with a size of 28, then bubble sort and output said array.
I've looked into other threads concerning this, and have tried to implement their solution with little to no success.
I output the array before and after the bubble sort, and it lists the array perfectly fine. The problem comes while trying to output the sorted array. Instead of listing the numbers in order, it gives me numbers such as 0,0,0,0,0,0,0,0,0,1,8,66,2292876,3012834, and so on.
I'd really like to get this program working and any and all help will be greatly appreciated.
P.S. I plan to write this code as seperate functions as well as add in other things. This is just a preliminary step and I'd like to get this resolved so I don't have to deal with several dozen more lines of code to debug on top of this.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
#define SIZE 28
int main ()
{
int array[SIZE], X;
ifstream data;
data.open("grades.txt");
data >> array[X];
while(! data.eof())
{
data >> array[X];
cout << array[X] << endl;
}
data.close();
cout << "\n\n\nContinue!\n\n\n";
cin.get();
int i, j, tmp;
for (i = 0; i < SIZE - 1; ++i)
{
for (j = 0; j < SIZE - i - 1; ++j)
{
if (array[j] > array[j + 1])
{
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
for(int C = 0; C < SIZE; C++)
cout << array[C] << endl;
return 0;
}
You don't initialize X
before you use it to index the array. And then you never
increment X
after reading data into the array, so all your input numbers are
being stored in the same location. Each one wipes out the memory of the
one that was read before it.
The only reason it appears that you are able to print the original array correctly is that you print each value you read immediately after you read it, before you wipe it out by storing the next value in that location. If you had separate functions to load the array and print the array, the print loop would occur after the input loop finished and you would see just how bad your input was.
You might consider this as a question for https://codereview.stackexchange.com/. A major part of the reason for this error is your programming style, which frankly needs a lot of work. (Nothing to be ashamed of, you're new at this and you haven't learned the ropes yet.) The separation of functions (input vs. output) that I mentioned in the previous paragraph is one of the aspects of programming style. Likewise the uninitialized variable, which would be much less likely if you used a preferable style of loop control logic.